(一)认识Django框架
Django 是一个由 Python 编写的一个开放源代码的 Web 应用框架。 使用 Django,只要很少的代码,Python 的程序开发人员就可以轻松地完成一个正式网站所需要的大部分内容,并进一步开发出全功能的 Web 服务 Django 本身基于 MVC 模型,即 Model(模型)+ View(视图)+ Controller(控制器)设计模式,MVC 模式使后续对程序的修改和扩展简化,并且使程序某一部分的重复利用成为可能.
(二)安装Django框架两种方式
第一种:通过pip安装
pip install django -i pypi.tuna.tsinghua.edu.cn/simple
第二种:通过源码方式安装(pypi.org/)
python setup.py install
(三)卸载Django框架
pip uninstall django
(四)查看Django版本
import django
django.__version__
# or
# django.get_version()
(五)创建Django项目 释:[.py] 可有可无
django-admin[.py] startproject my_project # 创建django项目
(六)创建项目模块
python manage.py startapp hello # 创建django项目的模块
(七)启动服务器
- 默认启动127.0.0.1
python manage.py runserver [prot]
- 自定义ip和端口
python manage.py runserver 0.0.0.0:8000 // 自定义端口
(八)实现第一个hello world
- views.py
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def hello_world(request):
return HttpResponse('hello-world')
- urls.py
from django.contrib import admin
from django.urls import path
from hello.views import hello_world
urlpatterns = [
path('admin/', admin.site.urls),
path('hello/',hello_world),
]
(九) 初实Django内置的include方法
- my_project.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('hello/', include('hello.urls')),
]
- 在hello模块中新建一个urls.py文件来管理hello模块的路由,将主路由跟模块路由分开,更好的维护项目路由
- hello/urls/urls.py
from django.urls import path
from hello.views import hello_world, hello_china
urlpatterns = [
path('world/',hello_world, name='hello_world'),
path('china/', hello_china, name='hello_china'),
]
疑难杂症
- 1.出现下面这个错误时,只需要在 setttings文件中配置一下启动ip即可:
ALLOWED_HOSTS = ['192.168.56.1','127.0.0.1']
# DisallowedHost at /hello/
Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add '127.0.0.1' to ALLOWED_HOSTS.