Django 入门

来自CloudWiki
跳转至: 导航搜索

安装django

第一步,进入命令提示符,切换至Python安装目录下的scripts目录,执行命令pip install django安装django扩展库。

创建项目

第二步,使用命令创建网站项目helloworld,进入项目文件夹,创建项目mainsite,如图:

C:\Users\thinkpad>cd C:\Users\thinkpad\AppData\Local\Programs\Python\Python37\Scripts

C:\Users\thinkpad\AppData\Local\Programs\Python\Python37\Scripts>django-admin startproject helloworld
CommandError: 'C:\Users\thinkpad\AppData\Local\Programs\Python\Python37\Scripts\helloworld' already exists


项目文件结构

manage.py

manage.py是与项目进行交互的命令行工具集的入口,是Django中的项目管理器,运行命令:

python manage.py 可以查看manage.py 的相关命令,其中最常用的是* runserver *命令,

helloworld

这个目录是项目的一个容器,包含项目的一些基本配置,文件名理论上可以随意修改,但并不建议这样做。这是因为配置文件中很多配置引用到这个文件名,如果修改,将会牵一发而动全身,带来不必要的麻烦。

接下来是helloworld目录下的.py文件:

1.wsgi.py

wsgi(Python Web Server Gateway Interface)即Python服务器网关接口,是python应用与Web服务器之间的接口。

2.urls.py

URL配置文件。Django项目中所有地址(页面)都需要我们去配置URL。

3.settins.py

4.init.py

声明模块,内容默认为空。

创建应用

C:\Users\thinkpad\AppData\Local\Programs\Python\Python37\Scripts>cd helloworld

C:\Users\thinkpad\AppData\Local\Programs\Python\Python37\Scripts\helloworld>python manage.py startapp mainsite

应用目录介绍

  • migrations:一个数据迁移的模块,内容自动生成
  • admin.py 该应用的后台管理系统
  • apps.py 该应用的一些配置,Django-1.9以后自动生成
  • models.py 数据模块,使用ORM框架
  • tests.py 自动化测试的模块
  • views.py 执行响应的代码所在模块,是代码逻辑处理的主要地点,项目中大部分代码在这里编写


修改文件

第三步,打开网站项目helloworld\mainsite\views.py文件进行修改,修改为:

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.

def index(request):
    return HttpResponse('Hello world!')

设置路由

第四步,打开网站项目helloworld\helloworld\urls.py文件设置url对应关系,下图中红框内是增加的代码,表示访问网站根目录时由mainsite\views.py中的index()函数来解析和处理。

from django.contrib import admin
from django.urls import path
from mainsite import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.index),
]

启动网站

第五步,在命令提示符环境中进入网站项目文件夹,执行命令启动网站,如图,runserver后面不带参数的话表示默认地址为127.0.0.1:8000,也可以使用参数来制定访问地址。启动后可以放置这个命令提示符窗口不用管,以后修改了网站中任何文件时,django会自动检测和更新。

python manage.py runserver

访问网站

第六步,打开浏览器,访问网站,如图:

Python10-2.png

参考文档:

https://mp.weixin.qq.com/s?__biz=MzI4MzM2MDgyMQ==&mid=2247484609&idx=1&sn=72344dfcc8d164733e8b5c2a8fbf0121&chksm=eb8aaf9bdcfd268daf27202d41742a3df645ab1213f10a05634e2acafb9e64ff4c260cf56c85&scene=21#wechat_redirect

https://www.jianshu.com/p/9b2ed154b616