Python Django 3.1.5

说明:所有操作均在CentOS7的Python虚拟环境操作,怎么搭建Python虚拟环境,请看我的另外一篇博文Python虚拟环境搭建

pip安装django

(django) [root@golang opt]# pip3 install django -i https://mirrors.aliyun.com/simple
(django) [root@golang HelloDjango]# django-admin --version
3.1.5

创建一个django项目

django-admin startproject HelloDjango

查看项目目录

tree HelloDjango/
HelloDjango/
├── HelloDjango
│   ├── asgi.py
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└── manage.py

1 directory, 6 files

说明:manage.py为项目管理文件,后期的项目管理全部由这个实现。
init.py代表该文件夹是一个包,可以用import导入。
settings.py项目全局设置。
urls.py路由器。
wsgi.py wsgi全称web service gateway interface,初期没什么用,项目上线的时候用,部署用。

python manage.py startapp App报错解决

报错

python manage.py startapp App
Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    main()
  File "manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "/opt/django/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "/opt/django/lib/python3.6/site-packages/django/core/management/__init__.py", line 377, in execute
    django.setup()
  File "/opt/django/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/opt/django/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate
    app_config.import_models()
  File "/opt/django/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models
    self.models_module = import_module(models_module_name)
  File "/opt/django/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 978, in _gcd_import
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
  File "/opt/django/lib/python3.6/site-packages/django/contrib/auth/models.py", line 2, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "/opt/django/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 48, in <module>
    class AbstractBaseUser(models.Model):
  File "/opt/django/lib/python3.6/site-packages/django/db/models/base.py", line 122, in __new__
    new_class.add_to_class('_meta', Options(meta, app_label))
  File "/opt/django/lib/python3.6/site-packages/django/db/models/base.py", line 326, in add_to_class
    value.contribute_to_class(cls, name)
  File "/opt/django/lib/python3.6/site-packages/django/db/models/options.py", line 206, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "/opt/django/lib/python3.6/site-packages/django/db/__init__.py", line 28, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "/opt/django/lib/python3.6/site-packages/django/db/utils.py", line 214, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "/opt/django/lib/python3.6/site-packages/django/db/utils.py", line 111, in load_backend
    return import_module('%s.base' % backend_name)
  File "/opt/django/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "/opt/django/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 14, in <module>
    from sqlite3 import dbapi2 as Database
  File "/usr/local/lib/python3.6/sqlite3/__init__.py", line 23, in <module>
    from sqlite3.dbapi2 import *
  File "/usr/local/lib/python3.6/sqlite3/dbapi2.py", line 27, in <module>
    from _sqlite3 import *
ModuleNotFoundError: No module named '_sqlite3'

解决

不用退出虚拟环境,新开一个连接窗口。
安装依赖

yum install sqlite*

重新编译安装Python3

rm -rf Python-3.6.0
tar zxvf Python-3.6.0.tgz
cd Python-3.6.0
./configure 
make && make install

继续报错

(django) [root@golang HelloDjango]# python manage.py startapp App
Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    main()
  File "manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "/opt/django/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "/opt/django/lib/python3.6/site-packages/django/core/management/__init__.py", line 377, in execute
    django.setup()
  File "/opt/django/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/opt/django/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate
    app_config.import_models()
  File "/opt/django/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models
    self.models_module = import_module(models_module_name)
  File "/opt/django/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 978, in _gcd_import
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
  File "/opt/django/lib/python3.6/site-packages/django/contrib/auth/models.py", line 2, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "/opt/django/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 48, in <module>
    class AbstractBaseUser(models.Model):
  File "/opt/django/lib/python3.6/site-packages/django/db/models/base.py", line 122, in __new__
    new_class.add_to_class('_meta', Options(meta, app_label))
  File "/opt/django/lib/python3.6/site-packages/django/db/models/base.py", line 326, in add_to_class
    value.contribute_to_class(cls, name)
  File "/opt/django/lib/python3.6/site-packages/django/db/models/options.py", line 206, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "/opt/django/lib/python3.6/site-packages/django/db/__init__.py", line 28, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "/opt/django/lib/python3.6/site-packages/django/db/utils.py", line 214, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "/opt/django/lib/python3.6/site-packages/django/db/utils.py", line 111, in load_backend
    return import_module('%s.base' % backend_name)
  File "/opt/django/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "/opt/django/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 70, in <module>
    check_sqlite_version()
  File "/opt/django/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 67, in check_sqlite_version
    raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version)
django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17).

给django降版本

(django) [root@golang HelloDjango]# pip install django==2.1.8 -i https://mirrors.aliyun.com/pypi/simple
Looking in indexes: https://mirrors.aliyun.com/pypi/simple
Collecting django==2.1.8
  Downloading https://mirrors.aliyun.com/pypi/packages/a9/e4/fb8f473fe8ee659859cb712e25222243bbd55ece7c319301eeb60ccddc46/Django-2.1.8-py3-none-any.whl (7.3 MB)
     |████████████████████████████████| 7.3 MB 1.2 MB/s 
Requirement already satisfied: pytz in /opt/django/lib/python3.6/site-packages (from django==2.1.8) (2020.5)
Installing collected packages: django
  Attempting uninstall: django
    Found existing installation: Django 3.1.5
    Uninstalling Django-3.1.5:
      Successfully uninstalled Django-3.1.5
Successfully installed django-2.1.8

继续报错,看来给django降级的方案行不通。采用另一种方案,安装高版本的sqlite。

(django) [root@golang HelloDjango]# python manage.py startapp app
Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    main()
  File "manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "/opt/django/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "/opt/django/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/opt/django/lib/python3.6/site-packages/django/core/management/base.py", line 336, in run_from_argv
    connections.close_all()
  File "/opt/django/lib/python3.6/site-packages/django/db/utils.py", line 224, in close_all
    connection.close()
  File "/opt/django/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 248, in close
    if not self.is_in_memory_db():
  File "/opt/django/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 367, in is_in_memory_db
    return self.creation.is_in_memory_db(self.settings_dict['NAME'])
  File "/opt/django/lib/python3.6/site-packages/django/db/backends/sqlite3/creation.py", line 12, in is_in_memory_db
    return database_name == ':memory:' or 'mode=memory' in database_name
TypeError: argument of type 'PosixPath' is not iterable

升级sqlite版本

wget https://www.sqlite.org/2019/sqlite-autoconf-3270200.tar.gz
tar zxvf sqlite-autoconf-3270200.tar.gz 
cd sqlite-autoconf-3270200
./configure --prefix=/usr/local
make && make install
mv /usr/bin/sqlite3 /usr/bin/sqlite3.bak
ln -s /usr/local/bin/sqlite3 /usr/bin/sqlite3
sqlite3 --version
export LD_LIBRARY_PATH="/usr/local/lib"
echo 'export LD_LIBRARY_PATH="/usr/local/lib"' >> /etc/profile
source /etc/profile

django切回到高版本

(django) [root@golang HelloDjango]# pip3 install -U django -i https://mirrors.aliyun.com/pypi/simple

注意项目名字不能是app

(django) [root@golang HelloDjango]# python manage.py startapp app
CommandError: 'app' conflicts with the name of an existing Python module and cannot be used as an app name. Please try another name.

创建一个app

(django) [root@golang HelloDjango]# python manage.py startapp runserver
(django) [root@golang HelloDjango]# tree runserver/
runserver/
├── admin.py
├── apps.py
├── __init__.py
├── migrations
│   └── __init__.py
├── models.py
├── tests.py
└── views.py

1 directory, 7 files

migrations和数据库对接用。
models.py 封装和数据的操作。
test.py 单元测试代码。
view.py视图函数。

python manage.py runserver报错解决

python /opt/django/HelloDjango/manage.py runserver 192.168.229.120:8000
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).

You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
January 15, 2021 - 03:01:13
Django version 3.1.5, using settings 'HelloDjango.settings'
Starting development server at http://192.168.229.120:8000/
Quit the server with CONTROL-C.

报错

在这里插入图片描述

解决

vim /opt/django/HelloDjango/HelloDjango/settings.py
找到ALLOWED_HOSTS=[],修改成如下
ALLOWED_HOSTS = ['192.168.229.120']

运行项目

python /opt/django/HelloDjango/manage.py runserver 192.168.229.120:8000
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).

You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
January 15, 2021 - 03:01:13
Django version 3.1.5, using settings 'HelloDjango.settings'
Starting development server at http://192.168.229.120:8000/
Quit the server with CONTROL-C.

web界面访问

在这里插入图片描述

设置语言编码

vim /opt/django/HelloDjango/HelloDjango/settings.py
LANGUAGE_CODE = 'zh-hans'

说明:修改python代码后已经运行的django会自动重启,直接访问即可。
在这里插入图片描述

填充数据库

python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying sessions.0001_initial... OK

登录

http://192.168.229.120:8000/admin/
在这里插入图片描述

自己写一个网页

修改urls.py

cat  HelloDjango/urls.py
"""HelloDjango URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from runserver import views #这句是新增的


urlpatterns = [
    path('admin/', admin.site.urls),
    path('hello/',views.hello), #这句是新增的
]

修改views.py

cat runserver/views.py
from django.shortcuts import render
from django.http import HttpResponse #这句是新增的

# Create your views here.

#hello函数是新增的
def hello(request):
   return HttpResponse('测试页面')

访问

说明:修改python代码后已经运行的django会自动重启,直接访问即可。
http://192.168.229.120:8000/hello/
在这里插入图片描述

简单渲染字体

修改urls.py

cat HelloDjango/urls.py
from django.contrib import admin
from django.urls import path
from runserver import views


urlpatterns = [
    path('admin/', admin.site.urls),
    path('hello/',views.hello),
    path('hello2/',views.hello2), #新增语句
]

修改views.py

cat  runserver/views.py 
from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def hello(request):
   return HttpResponse('测试页面')
  
#新增函数
def hello2(request):
   return HttpResponse('<h1>测试页面</h1>')

访问

http://192.168.229.120:8000/hello2/
在这里插入图片描述

制作复杂的html页面

写一个模板

mkdir /opt/django/HelloDjango/runserver/templates

cat /opt/django/HelloDjango/runserver/templates/index.html
<div class="header">
  <h1>菜鸟教程网页测试实例</h1>
  <p>创建一个页面。</p>
</div>
 
<div class="navbar">
  <a href="#">链接</a>
  <a href="#">链接</a>
  <a href="#">链接</a>
  <a href="#" class="right">链接</a>
</div>
 
<div class="row">
  <div class="side">
      <h2>关于我</h2>
      <h5>我的照片:</h5>
      <div class="fakeimg" style="height:200px;">这边插入图像</div>
      <p>关于我的介绍..</p>
      <h3>更多内容</h3>
      <p>我的更多内容</p>
      <div class="fakeimg" style="height:60px;">这边插入图像</div><br>
      <div class="fakeimg" style="height:60px;">这边插入图像</div><br>
      <div class="fakeimg" style="height:60px;">这边插入图像</div>
  </div>
  <div class="main">
      <h2>标题</h2>
      <h5>副标题</h5>
      <div class="fakeimg" style="height:200px;">图像</div>
      <p>一些文本..</p>
      <p>菜鸟教程,学的不仅是技术,更是梦想!!!菜鸟教程,学的不仅是技术,更是梦想!!!菜鸟教程,学的不仅是技术,更是梦想!!!</p>
      <br>
      <h2>标题</h2>
      <h5>副标题</h5>
      <div class="fakeimg" style="height:200px;">图像</div>
      <p>一些文本..</p>
      <p>菜鸟教程,学的不仅是技术,更是梦想!!!菜鸟教程,学的不仅是技术,更是梦想!!!菜鸟教程,学的不仅是技术,更是梦想!!!</p>
  </div>
</div>
 
<div class="footer">
  <h2>底部内容</h2>
</div>

修改urls.py

cat    HelloDjango/urls.py
from django.contrib import admin
from django.urls import path
from runserver import views


urlpatterns = [
    path('admin/', admin.site.urls),
    path('hello/',views.hello),
    path('hello2/',views.hello2),
    path('cloud/',views.cloud), #新增语句
]

修改views.py

cat runserver/views.py 
from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def hello(request):
   return HttpResponse('测试页面')
  

def hello2(request):
   return HttpResponse('<h1>测试页面</h1>')

#新增函数
def cloud(request):
   return render(request,'index.html')

访问

http://192.168.229.120:8000/cloud/
在这里插入图片描述
这是因为runserver没有被识别

vim HelloDjango/settings.py
#在INSTALLED_APPS下新增一个项目runserver
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'runserver',
]

再次访问

http://192.168.229.120:8000/cloud/
在这里插入图片描述

返回一个图片

改html文件

在上一节基础上直接改html文件

cat /opt/django/HelloDjango/runserver/templates/index.html
{% load static %}
   <div class="main-main">
   <div>
      <img src="{% static 'images/test.jpg' %}" alt="">
   </div>
   </div>

创建图片所在目录

mkdir -p /opt/django/HelloDjango/static/images/
cd /opt/django/HelloDjango/static/images/

上传一个test.jpg的图片

ll
总用量 56
-rw-r--r--. 1 root root 56017 1月  15 14:48 test.jpg

改setting.py
导入os模块并在最后一行增加如下代码

cat /opt/django/HelloDjango/HelloDjango/settings.py
import os
cat /opt/django/HelloDjango/HelloDjango/settings.py
STATICFILES_DIRS=(
    os.path.join(BASE_DIR,'static'),
)

说明:这里的BASE_DIR是在settings.py文件里定义的一个变量,原文如下

cat /opt/django/HelloDjango/HelloDjango/settings.py|grep BASE_DIR
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
        'NAME': BASE_DIR / 'db.sqlite3',
    os.path.join(BASE_DIR,'static'),

Path(file).resolve().parent.parent表示settings.py这个文件所在目录的上两层目录,settings.py所在目录为/opt/django/HelloDjango/HelloDjango/,他的上两层目录即为/opt/django/HelloDjango/,os.path.join表示目录拼接,那么这个图片的目录就应该是/opt/django/HelloDjango/static/images/。

访问

http://192.168.229.120:8000/cloud/
在这里插入图片描述

调整图片位置

改html文件

在上一节基础上直接改html文件

cat runserver/templates/index.html
<style type="text/css">
.imgdiv{
     
     
width:400px;
height:400px;
border:1px solid
}
.imgdiv img{
     
     
margin-top:20px;
padding-left:20px;
}

</style>

{% load static %}
   <div class="imgdiv">
   <div>
      <img src="{% static 'images/test.jpg' %}" alt="">
   </div>
   </div>

访问

http://192.168.229.120:8000/cloud/
在这里插入图片描述
可以看到,图片位置已经移动。

创建新目录

在项目HelloDjango根目录/opt/django/HelloDjango下,创建一个templates目录

mkdir /opt/django/HelloDjango/templates/

写html文件

cat  /opt/django/HelloDjango/templates/home.html 
<style type="text/css">
.imgdiv{
     
     
width:400px;
height:400px;
border:1px solid
}
.imgdiv img{
     
     
margin-top:20px;
padding-left:20px;
}

</style>

{% load static %}
   <div class="imgdiv">
   <div>
      <img src="{% static 'images/test.jpg' %}" alt="">
   </div>
   </div>

修改urls.py

cat /opt/django/HelloDjango/HelloDjango/urls.py
from django.contrib import admin
from django.urls import path
from runserver import views


urlpatterns = [
    path('admin/', admin.site.urls),
    path('hello/',views.hello),
    path('hello2/',views.hello2),
    path('cloud/',views.cloud),
    path('home/',views.home), #新增语句
]

修改views.py

cat /opt/django/HelloDjango/runserver/views.py 
from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def hello(request):
   return HttpResponse('测试页面')
  

def hello2(request):
   return HttpResponse('<h1>测试页面</h1>')
   
def cloud(request):
   return render(request,'index.html')
#新增函数
def home(request):
   return render(request,'home.html')

访问

http://192.168.229.120:8000/home/
在这里插入图片描述

修改setting.py

在TEMPLATES下的DIRS下将新建的目录加上。

TEMPLATES = [
    {
    
       
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
         os.path.join(BASE_DIR,'templates'),
         ],
        'APP_DIRS': True,
        'OPTIONS': {
    
    
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

再次访问

http://192.168.229.120:8000/home/
在这里插入图片描述

快速制作网页

复制网页代码

随便从网页上复制代码粘贴到/opt/django/HelloDjango/templates/home.html文件里

访问

http://192.168.229.120:8000/home/
在这里插入图片描述
说明:这里边的视频是不可以看的。

猜你喜欢

转载自blog.csdn.net/weixin_40548182/article/details/112647899