欢迎来到海上华帆的博客园子

记录一些学习过程中的心得体会,供自己和有缘人参考!

Ubungu+Django简单项目创建代码全

Ubungu+Django简单项目创建代码全

操作要点

创建虚拟环境python3 -m venv venv

激活虚拟环境source venv/bin/activate

安装django pip install django -i https://pypi.mirrors.ustc.edu.cn/simple

创建django项目 django-admin startproject djangoweb

修改项目settings.py字段ALLOW_HOSTS = ['*']

数据库迁移 python3 manage.py migrate

创建项目应用程序app django-admin startapp app1

注册app到项目settings.py中的INSTALLED_APPS字段添加'app1',

app目录新增视图views.py和路由文件urls.py

项目路由urls.py包含app路由文件

项目启动 python3 manage.py runserver 0.0.0.0:8000

先创建一个超级用户(superuser)才能登录到后台管理界面

python3 manage.py superuser

点击查看代码
连接主机...
连接主机成功
Welcome to Ubuntu 22.04.4 LTS (GNU/Linux 5.15.0-105-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/pro

  System information as of Sat May 25 08:46:57 AM UTC 2024

  System load:  0.240234375        Processes:             198
  Usage of /:   17.8% of 27.86GB   Users logged in:       0
  Memory usage: 7%                 IPv4 address for eth0: 192.168.2.101
  Swap usage:   0%


Expanded Security Maintenance for Applications is not enabled.

19 updates can be applied immediately.
To see these additional updates run: apt list --upgradable

Enable ESM Apps to receive additional future security updates.
See https://ubuntu.com/esm or run: sudo pro status


The list of available updates is more than a week old.
To check for new updates run: sudo apt update

Last login: Fri Apr 19 10:39:51 2024
To run a command as administrator (user "root"), use "sudo <command>".
See "man sudo_root" for details.

lyh@u1:~$ python3 -V
Python 3.10.12
lyh@u1:~$ sudo apt install python3-venv
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following additional packages will be installed:
  python3-pip-whl python3-setuptools-whl python3.10-venv
The following NEW packages will be installed:
  python3-pip-whl python3-setuptools-whl python3-venv python3.10-venv
0 upgraded, 4 newly installed, 0 to remove and 20 not upgraded.
Need to get 2,474 kB of archives.
After this operation, 2,890 kB of additional disk space will be used.
Do you want to continue? [Y/n] Y
Get:1 http://cn.archive.ubuntu.com/ubuntu jammy-updates/universe amd64 python3-pip-whl all 22.0.2+dfsg-1ubuntu0.4 [1,680 kB]
Get:2 http://mirrors.tuna.tsinghua.edu.cn/ubuntu jammy-updates/universe amd64 python3-setuptools-whl all 59.6.0-1.2ubuntu0.22.04.1 [788 kB]
Get:3 http://cn.archive.ubuntu.com/ubuntu jammy-updates/universe amd64 python3.10-venv amd64 3.10.12-1~22.04.3 [5,716 B]
Get:4 http://cn.archive.ubuntu.com/ubuntu jammy-updates/universe amd64 python3-venv amd64 3.10.6-1~22.04 [1,038 B]
Fetched 2,474 kB in 2s (1,327 kB/s)
Selecting previously unselected package python3-pip-whl.
(Reading database ... 74559 files and directories currently installed.)
Preparing to unpack .../python3-pip-whl_22.0.2+dfsg-1ubuntu0.4_all.deb ...

Progress: [  0%] [....................................................................................................................] 
Unpacking python3-pip-whl (22.0.2+dfsg-1ubuntu0.4) ...................................................................................] 

Selecting previously unselected package python3-setuptools-whl........................................................................] 
Preparing to unpack .../python3-setuptools-whl_59.6.0-1.2ubuntu0.22.04.1_all.deb ...

Unpacking python3-setuptools-whl (59.6.0-1.2ubuntu0.22.04.1) .........................................................................] 

Selecting previously unselected package python3.10-venv...............................................................................] 
Preparing to unpack .../python3.10-venv_3.10.12-1~22.04.3_amd64.deb ...

Unpacking python3.10-venv (3.10.12-1~22.04.3) ...###..................................................................................] 

Selecting previously unselected package python3-venv.#####............................................................................] 
Preparing to unpack .../python3-venv_3.10.6-1~22.04_amd64.deb ...

Unpacking python3-venv (3.10.6-1~22.04) ...######################.....................................................................] 

Setting up python3-setuptools-whl (59.6.0-1.2ubuntu0.22.04.1) ...#######..............................................................] 

Progress: [ 53%] [#############################################################.......................................................] 
Setting up python3-pip-whl (22.0.2+dfsg-1ubuntu0.4) ...###############################................................................] 

Progress: [ 65%] [###########################################################################.........................................] 
Setting up python3.10-venv (3.10.12-1~22.04.3) ...#################################################...................................] 

Progress: [ 76%] [########################################################################################............................] 
Setting up python3-venv (3.10.6-1~22.04) ...#####################################################################.....................] 

Progress: [ 88%] [######################################################################################################..............] 
Scanning processes...                                                                                                                     
Scanning linux images...                                                                                                                  

Running kernel seems to be up-to-date.

No services need to be restarted.

No containers need to be restarted.

No user sessions are running outdated binaries.

No VM guests are running outdated hypervisor (qemu) binaries on this host.
lyh@u1:~$ mkdir django
lyh@u1:~$ cd django
lyh@u1:~/django$ python3 -m venv venv
lyh@u1:~/django$ source venv/bin/activate
(venv) lyh@u1:~/django$ pip install django -i https://pypi.mirrors.ustc.edu.cn/simple
Looking in indexes: https://pypi.mirrors.ustc.edu.cn/simple
Collecting django
  Downloading https://mirrors.bfsu.edu.cn/pypi/web/packages/1d/23/02f3795a71196019bcfec4c67890a6369e43b023474154fa0b2b7060346d/Django-5.0.6-py3-none-any.whl (8.2 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 8.2/8.2 MB 9.6 MB/s eta 0:00:00
Collecting sqlparse>=0.3.1
  Downloading https://mirrors.bfsu.edu.cn/pypi/web/packages/43/5d/a0fdd88fd486b39ae1fd1a75ff75b4e29a0df96c0304d462fd407b82efe0/sqlparse-0.5.0-py3-none-any.whl (43 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 44.0/44.0 KB 6.5 MB/s eta 0:00:00
Collecting asgiref<4,>=3.7.0
  Downloading https://mirrors.bfsu.edu.cn/pypi/web/packages/39/e3/893e8757be2612e6c266d9bb58ad2e3651524b5b40cf56761e985a28b13e/asgiref-3.8.1-py3-none-any.whl (23 kB)
Collecting typing-extensions>=4
  Downloading https://mirrors.bfsu.edu.cn/pypi/web/packages/e1/4d/d612de852a0bc64a64418e1cef25fe1914c5b1611e34cc271ed7e36174c8/typing_extensions-4.12.0-py3-none-any.whl (37 kB)
Installing collected packages: typing-extensions, sqlparse, asgiref, django
Successfully installed asgiref-3.8.1 django-5.0.6 sqlparse-0.5.0 typing-extensions-4.12.0
(venv) lyh@u1:~/django$ django-admin startproject djangoweb
(venv) lyh@u1:~/django$ cd djangoweb
(venv) lyh@u1:~/django/djangoweb$ ls
djangoweb  manage.py
(venv) lyh@u1:~/django/djangoweb$ python3 manage.py runserver 0.0.0.0: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.
May 25, 2024 - 09:01:45
Django version 5.0.6, using settings 'djangoweb.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.

Invalid HTTP_HOST header: '192.168.2.101:8000'. You may need to add '192.168.2.101' to ALLOWED_HOSTS.
Traceback (most recent call last):
  File "/home/lyh/django/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/home/lyh/django/venv/lib/python3.10/site-packages/django/utils/deprecation.py", line 133, in __call__
    response = self.process_request(request)
  File "/home/lyh/django/venv/lib/python3.10/site-packages/django/middleware/common.py", line 48, in process_request
    host = request.get_host()
  File "/home/lyh/django/venv/lib/python3.10/site-packages/django/http/request.py", line 151, in get_host
    raise DisallowedHost(msg)
django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: '192.168.2.101:8000'. You may need to add '192.168.2.101' to ALLOWED_HOSTS.
Bad Request: /
[25/May/2024 09:01:55] "GET / HTTP/1.1" 400 63474
Invalid HTTP_HOST header: '192.168.2.101:8000'. You may need to add '192.168.2.101' to ALLOWED_HOSTS.
Traceback (most recent call last):
  File "/home/lyh/django/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/home/lyh/django/venv/lib/python3.10/site-packages/django/utils/deprecation.py", line 133, in __call__
    response = self.process_request(request)
  File "/home/lyh/django/venv/lib/python3.10/site-packages/django/middleware/common.py", line 48, in process_request
    host = request.get_host()
  File "/home/lyh/django/venv/lib/python3.10/site-packages/django/http/request.py", line 151, in get_host
    raise DisallowedHost(msg)
django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: '192.168.2.101:8000'. You may need to add '192.168.2.101' to ALLOWED_HOSTS.
Bad Request: /
[25/May/2024 09:01:55] "GET / HTTP/1.1" 400 63200
^C(venv) lyh@u1:~/django/djangoweb$ 
^C(venv) lyh@u1:~/django/djangoweb$ 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
(venv) lyh@u1:~/django/djangoweb$ 
(venv) lyh@u1:~/django/djangoweb$ cat djangoweb/settings.py
"""
Django settings for djangoweb project.

Generated by 'django-admin startproject' using Django 5.0.6.

For more information on this file, see
https://docs.djangoproject.com/en/5.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.0/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-+l^&hrinq^gyvcm!$o_$@ru7nqnbo_k6&0mnt^tu@+j=9m)cra'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'djangoweb.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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',
            ],
        },
    },
]

WSGI_APPLICATION = 'djangoweb.wsgi.application'


# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/5.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
(venv) lyh@u1:~/django/djangoweb$ 
(venv) lyh@u1:~/django/djangoweb$ vim djangoweb/settings.py
(venv) lyh@u1:~/django/djangoweb$ python3 manage.py runserver 0.0.0.0:8000
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
May 25, 2024 - 09:08:35
Django version 5.0.6, using settings 'djangoweb.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.


^C(venv) lyh@u1:~/django/djangoweb$ django-admin startapp app1
(venv) lyh@u1:~/django/djangoweb$ ls
app1  db.sqlite3  djangoweb  manage.py
(venv) lyh@u1:~/django/djangoweb$ cd app1
(venv) lyh@u1:~/django/djangoweb/app1$ ls
admin.py  apps.py  __init__.py  migrations  models.py  tests.py  views.py
(venv) lyh@u1:~/django/djangoweb/app1$ 
(venv) lyh@u1:~/django/djangoweb/app1$ vim views.py
(venv) lyh@u1:~/django/djangoweb/app1$ cat views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.


def index(request):
    return HttpResponse("Hello,world. You're at the app1 index.")
(venv) lyh@u1:~/django/djangoweb/app1$ 
(venv) lyh@u1:~/django/djangoweb/app1$ vim urls.py
(venv) lyh@u1:~/django/djangoweb/app1$ cat urls.py
from django.urls import path
from . import views


urlpatterns = [
        path('', views.index, name='index'),
        ]
(venv) lyh@u1:~/django/djangoweb/app1$ 
(venv) lyh@u1:~/django/djangoweb/app1$ cd ..
(venv) lyh@u1:~/django/djangoweb$ vim djangoweb/urls.py
(venv) lyh@u1:~/django/djangoweb$ cat djangoweb/urls.py
"""
URL configuration for djangoweb project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/5.0/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 django.urls import include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('app1/', include('app1.urls')),
    ]
(venv) lyh@u1:~/django/djangoweb$ 
(venv) lyh@u1:~/django/djangoweb$ vim djangoweb/settings.py
(venv) lyh@u1:~/django/djangoweb$ python3 manage.py runserver 0.0.0.0:8000
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
May 25, 2024 - 09:25:46
Django version 5.0.6, using settings 'djangoweb.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.

Not Found: /
[25/May/2024 09:25:50] "GET / HTTP/1.1" 404 2171
[25/May/2024 09:26:08] "GET /app1/ HTTP/1.1" 200 38
[25/May/2024 09:26:48] "GET /admin HTTP/1.1" 301 0
[25/May/2024 09:26:48] "GET /admin/ HTTP/1.1" 302 0
[25/May/2024 09:26:48] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 4158
[25/May/2024 09:26:48] "GET /static/admin/css/nav_sidebar.css HTTP/1.1" 200 2810
[25/May/2024 09:26:48] "GET /static/admin/css/dark_mode.css HTTP/1.1" 200 2682
[25/May/2024 09:26:48] "GET /static/admin/css/login.css HTTP/1.1" 200 958
[25/May/2024 09:26:48] "GET /static/admin/css/base.css HTTP/1.1" 200 21544
[25/May/2024 09:26:48] "GET /static/admin/css/responsive.css HTTP/1.1" 200 17905
[25/May/2024 09:26:48] "GET /static/admin/js/theme.js HTTP/1.1" 200 1943
[25/May/2024 09:26:48] "GET /static/admin/js/nav_sidebar.js HTTP/1.1" 200 3063
Not Found: /
[25/May/2024 09:28:01] "GET / HTTP/1.1" 404 2171
Not Found: /
[25/May/2024 09:28:01] "GET / HTTP/1.1" 404 2171

^C(venv) lyh@u1:~/django/djangoweb$ python manage.py createsuperuser
Username (leave blank to use 'lyh'): 
Email address: haishanghuafan@163.com        
Password: 
Password (again): 
This password is too short. It must contain at least 8 characters.
This password is entirely numeric.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.
(venv) lyh@u1:~/django/djangoweb$ 

ALLOW_HOSTS = ['*']

浏览器的结果

修改ALLOW_HOST = ['*']

在/djangoweb/settings.py中注册app1

访问http://192.168.2.101:8000

访问http://192.168.2.101:8000/app1

访问http://192.168.2.101:8000/admin

登录需要先创建一个超级用户(superuser)才能登录到后台管理界面。

posted @   海上华帆  阅读(34)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
点击右上角即可分享
微信分享提示