Basic commands of Django framework
django-admin startproject
# Create a Django projectdjango-admin startapp
# Create a Django application
Create a Django project
1. 打开cmd,cd到项目目录下,新建一个文件夹,然后cd到该文件夹下
2. 使用 # pipenv install 命令创建虚拟环境 #pipenv shell 进入虚拟环境
3.安装django: # pip install django
4.安装成功后,创建一个Django项目:# django-admin startproject [输入创建的项目名称]
5.创建一个Django应用: # django-admin startapp [应用名]
6.使用pycharm打开该项目,在file>>setting>>Python Interpreter中选择刚刚pipenv生成的环境。如图1-1
7.在Terminal中输入:# python manage.py runserver
如果运行成功则可以得到如下图1-2则表明前面的配置成功!!
Django之hello world
The contents of the project after initialization are as follows:
To run a hello world program, you first need to write the view function hello in views.py in the application-level file directory:
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def hello(request):
return HttpResponse('hello world')
Next, create a urls.py file under this project, and register the route of the hello function to the application level:
# login.urls.py
from django.urls import path
import login.views
urlpatterns = [
path('hello', login.views.hello)
]
But thinking about the application-level routing configuration, it is obvious that the project level cannot be understood. Just like the ID card registered in the local police station, the ID card is not transmitted to the national identity system, and the police outside will definitely only check when they are looking for you. There is no such person, so it needs to be configured at the application level. That is, the following registration behaviors are performed in the application level urls.py
and in the application level settings.py
:
# blog/urls.py
from django.contrib import admin
from django.urls import path,include
import login.views
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', include('login.urls'))
]
blog/settings.py
After completion, enter >>> in Terminal python manage.py runserver
Then enter in the browser: http://127.0.0.1:8000/login/hello
you can get the following hello world