Django是一个web框架,python编写的。

MTV模式

  1. DjangoMTV模式本质上和MVC是一样的,也是为了各组件间保持松耦合关系,只是定义上有些许不同
  2. -M代表模型(Model ):负责业务对象和数据库的关系映射(ORM)
  3. -T代表模板(Template):负责如何把页面展示给用户(html)
  4. -V代表视图(View ) :负责业务逻辑,并在适当时候调用ModelTemplate

  client(客户端)–>请求(url)–> server(服务器的urlconf)–>views(视图,相当于函数,客户机访问url,每次的访问都有相应的函数对应)–>model(数据库,增删改查)–>views(修改数据库后再返回信息给视图,数据交互)–>Template(web页面)–>client

  

一、创建python的虚拟环境

  (一)配置pip文件

  1. (django_env) [root@django ~]# cat .pip/pip.conf
  2. [global]
  3. index-url = http://pypi.douban.com/simple
  4. [install]
  5. trusted-host=pypi.douban.com

   (二)虚拟环境安装

  1. mkdir pyproject
  2. cd pyproject/
  3. python3 -m venv django_env #在当前目录创建虚拟环境(Django_env 名字可以变)
  4. source django_env/bin/activate #激活虚拟环境
  5. pip install django==1.11.6 #在虚拟环境中安装Django==1.11.6
  6. (django_env) [root@localhost pyproject]# python #验证
  7. Python 3.6.4 (default, Apr 27 2018, 08:26:23)
  8. [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
  9. Type "help", "copyright", "credits" or "license" for more information.
  10. >>> import django
  11. >>> django.__version__
  12. '1.11.6'

二 、Django项目创建

  1. django-admin startproject mysite #创建项目
  2. (django_env) [root@localhost pyproject]# cd mysite #Django的目录结构
  3. (django_env) [root@localhost mysite]# tree
  4. .
  5. ├── manage.py
  6. └── mysite
  7. ├── __init__.py
  8. ├── settings.py
  9. ├── urls.py
  10. └── wsgi.py

mysite:项目的容器。

manage.py:一个使用的命令行工具,可让你以各种方式与该django项目进行交互(项目的管理目录)

mysite/__init__.py:一个空文件,告诉python该目录是一个python包。(项目的初始化文件)

mysite/settings.py:该django项目的设置/配置。(项目的配置文件)

mysite/urls.py:该django项目的URL声明;一份由django驱动的网站“目录”。(项目的路由文件)

mysite/wsgi.py:一个WSGI兼容的Web服务器的入口,以便运行你的项目。(将网站部署到web服务器时使用的文件)

 python manage.py runserver 0.0.0.0:8000   #运行项目

 127.0.0.1:8000  #查看项目

 三、Django配置

  (一)创建数据库 

  1. CREATE DATABASE django DEFAULT CHARSET 'UTF8';

  (二)配置 setting.py(配置完成后页面变成中文)

  1. ALLOWED_HOSTS = ['*'] # 允许所有的客户端访问
  2. DATABASES = {
  3. 'default': {'ENGINE': 'django.db.backends.mysql',
  4. 'NAME': 'django',
  5. 'USER': 'root',
  6. 'PASSWORD': '数据库root密码',
  7. 'HOST': '127.0.0.1',
  8. 'PORT': '3306', }
  9. }
  10. LANGUAGE_CODE ='zh-hans' #中文
  11. TIME_ZONE ='Asia/Shanghai'
  12. USE_TZ = False

   (三)配置__init__.py(要先安装pymysql模块)

  1. import pymysql
  2. pymysql.install_as_MySQLdb()

   运行查看 

  1. # 重新运行测试服务器,监听在0.0.0.0的80端口。注意:如果不是root,不能监听1024以下端口
  2. [root@room8pc16 mysite]# python manage.py runserver 0:80
  3.  

  (四)生成数据  

  1. [root@room8pc16 mysite]#python manage.py makemigrations #会生成一些相应的sql语句
  2. [root@room8pc16 mysite]# python manage.py migrate #生成表

   (五)创建管理员 

  1. [root@room8pc16 mysite]# python manage.py createsuperuser #密码要求复杂度和长度

   查看页面

 四、使用Django创建应用

  (一)创建应用(对应的一个个的功能模块,使用一个投票为例子)

  1. [root@room8pc16 mysite]# python manage.py startapp polls #创建应用(可以集成到任何的一个项目中)

   (二)在settings配置文件中声明应用(把应用集成在项目中)

  1. INSTALLED_APPS = [
  2. 'django.contrib.admin',
  3. 'django.contrib.auth',
  4. 'django.contrib.contenttypes',
  5. 'django.contrib.sessions',
  6. 'django.contrib.messages',
  7. 'django.contrib.staticfiles',
  8. 'polls' #添加的应用
  9. ]

  (三)授权,把应用的url交给投票应用处理,都在项目下的urls.py的这个文件就会特别大

  1. polls/urls.py
  2. from django.conf.urls import url, include
  3. from django.contrib import adminurlpatterns = [
  4. # 正则匹配时,从http://x.x.x.x/后面开始算起
  5. # 正则匹配时,从http://x.x.x.x/polls
  6. url(r'^admin/', admin.site.urls),
  7. url(r'^polls/', include('polls.urls')), #其中r意思真实字符串相当于shell中的单引号
  8. ]

 

   在polls目录下没有urls.py文件就创建一个

  1. [root@django polls]# touch urls.py
  2. vim polls/urls.py
    from django.conf.urls import url
    urlpatterns = [
    ]

五、创建投票首页

  (一)编写url

  1. from django.conf.urls import url,include
  2. from django.contrib import admin
    from . import views #.是当前目录的意思(和urls.py同级,也可以from polls import views)
  3.  
  4. urlpatterns = [
  5. url(r'^$', views.index,name='index'), #匹配到空白,都用views.index函数进行响应,那么为函数名字
  6. ]

  (二)编写views视图函数

  1. def index(request):
  2. # 用户发起的请求将会作为第一个参数传给函数 (客户端发起请求时可能是 get,put,post,携带的参数或者数据等等 都会作为第一个参数 传给request)
  3. # 所以函数至少要定义一个参数来接收用户的请求
  4. # render负责找寻模板文件发送给用户
  5. return render(request, 'index.html')

   (三)编写页面(确定templates模板的位置)

  1. TEMPLATES = [
  2. {
  3. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  4. 'DIRS': [os.path.join(BASE_DIR, 'templates')], #templates模板的位置,项目目录同级
  5. 'APP_DIRS': True,
  6. 'OPTIONS': {
  7. 'context_processors': [
  8. 'django.template.context_processors.debug',
  9. 'django.template.context_processors.request',
  10. 'django.contrib.auth.context_processors.auth',
  11. 'django.contrib.messages.context_processors.messages',
  12. ],

   index.html

  1. <html lang="en">
  2. <head>
  3. <meta charset="UTF-8">
  4. <title>polls</title>
  5. </head>
  6. <body>
  7. <div class="container">
  8. <h1>polls</h1>
  9. </div>
  10. </body>
  11. </html>

 

 

 

 六、编写问题页面

  (一)编写urls.py

  1. urlpatterns = [
  2. url(r'^$', views.index,name='index'),
  3. url(r'(\d+)/$', views.a,name='a'),
  4. #\d+为匹配数字(+为至少匹配到一个数字)
  5. # ()为传参(把匹配到的数字作为视图函数a的参数 )
  6. ]

   (二)编写views.py

  1. from django.shortcuts import render
  2.  
  3. def index(request):
  4. return render(request,'index.html')
  5. def a(request,id): #在urls.py中匹配到的参数的值用变量id接受
  6. return render(request,'a.html',{'id':id})
  7.   # 字典的内容将会成为模板文件的变量,字典的key是变量名,value是变量值(字典的值成为html的参数)

   (三)编写a.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <div class="container">
  9. <h1>{{id}}question</h1> #在views.py文件中接受的参数,用{{}}表示
  10. </div>
  11. </body>
  12. </html>

 

 

 

 

 七、编写结果页面

  (一)编写urls.py

  1. urlpatterns = [
  2. url(r'^$', views.index,name='index'), #r‘’单引号里面什么也不填写那么就是匹配空串(在任何字符之间都有空串),不管在ip/polls/后面填写什么都将匹配首页
  3. url(r'(\d+)/$', views.a,name='a'),
  4. url(r'(\d+)/result/$', views.result,name='result')
  5. ]

   (二)编写views.py

  1. from django.shortcuts import render
  2.  
  3. # Create your views here.
  4. def index(request):
  5. return render(request,'index.html')
  6. def a(request,id):
  7. return render(request,'a.html',{'id':id})
  8. def result(request,id):
  9. return render(request,'result.html',{'id':id})

   (三)编写result.html

  1. <meta charset="UTF-8">
  2. <title>Title</title>
  3. </head>
  4. <body>
  5. <div>
  6. <h1>{{id}}result</h1>
  7. </div>
  8. </body>
  9. </html>

 八、model模型

  1. ORM
  2. object :对象﹐对应django模型中的class
  3. Relationship:关系﹐对应关系型数据库
  4. Mapping:映射
  5. 一个class对应数据库中的一张表
  6. 表中的字段与class中的类变量对应
  7. 数据库中的数据类型也与django模型中的类映射
  8. 表中的每个记录都与class的实例对应

   (一)编写models.py

  1. from django.db import models
  2.  
  3. # Create your models here.
  4. class Question(models.Model):
  5. question_text = models.CharField(max_length=200, unique=True)
  6. pub_date = models.DateTimeField() #不加Field,没有时分秒
  7. class Chioce(models.Model):
  8. chioce_text = models.CharField(max_length=200, unique=True)
  9. votes = models.IntegerField(default=0)
  10. question = models.ForeignKey(Question) #如果想要修改字段名,在配置文件中修改之后,重新生成表

   (二)生成表

  1. python manage.py makemigrations
  2. python manage.py migrate

   (三)将模型加入到后台页面

  1. # polls/admin.py
  2. from django.contrib import admin# 在当前目录下的models模块中导入模型
  3. from .models import Question, Choice
  4. # Register your models here.
  5. admin.site.register(Question)
  6. admin.site.register(Choice)

 

 

   解决办法

  1. class Question(models.Model):
  2. question_text = models.CharField(max_length=200, unique=True)
  3. pub_date = models.DateTimeField()
  4. def __str__(self):
  5. return 'question:%s' % self.question_text
  6. class Chioce(models.Model):
  7. chioce_text = models.CharField(max_length=200, unique=True)
  8. votes = models.IntegerField(default=0)
  9. question = models.ForeignKey(Question)
  10. def __str__(self):
  11. return '%s:%s' % return '%s:%s' % (self.question,self.chioce_text)

 

 

 九、Django API(首页)

   (一)在views文件中把问题取出来传给html

  1. # polls/views.py
  2. from django.shortcuts import render
  3. from .models import Question
  4. def index(request):
  5.   questions = Question.objects.order_by('-pub_date')
  6.   returnrender(request, 'index.html', {'questions': questions})

   (二)编辑index.html

  1. <!DOCTYPEhtml>
  2. <htmllang="en">
  3. <head>
  4. <metacharset="UTF-8">
  5. <title>投票首页</title>
  6. </head>
  7. <body>
  8. <div class="container">
  9. <div class="content">
  10. <h1>投票首页</h1>
  11. <ol>
  12. {% for question in questions %}
  13. <li>
  14. <a href="{% url 'a' question.id %}" target="_blank">
    #question_id是views.py中的\d+这个参数,数据库中没有指定主键时Django会自动创建主键,question_id就是问题的id号
  15. {{ question.question_text }}</a>
  16.      {{ question.pub_date }}
  17. </li>
  18. {%endfor%}
  19. </ol>
  20. </div>
  21. </div>
  22. </body>
  23. </html>

   (三)可以添加轮播图

  1. <div class="container">
  2. <div id="linux-carousel" class="carousel slide">
  3. <ol class="carousel-indicators">
  4. <li class="active" data-target="#linux-carousel" data-slide-to="0"></li> #轮播图下面的小圆点
  5. <li data-target="#linux-carousel" data-slide-to="1"></li>
  6. <li data-target="#linux-carousel" data-slide-to="2"></li>
  7. </ol>
  8. <div class="carousel-inner">
  9. <div class="item active">
  10. <a href="http://www.sogou.com" target="_blank">
  11. <img src="{% static 'imgs/first.jpg' %}">
  12. </a>
  13. </div>
  14. <div class="item">
  15. <img src="{% static 'imgs/second.jpg' %}">
  16. </div>
  17. <div class="item">
  18. <img src="{% static 'imgs/third.jpg' %}">
  19. </div>
  20. </div>
  21. <a href="#linux-carousel" data-slide="prev" class="carousel-control left"> <span class="glyphicon glyphicon-chevron-left"></span> #向左翻
  22. 制作投票详情页
  23. </a>
  24. <a href="#linux-carousel" data-slide="next" class="carousel-control right"> <span class="glyphicon glyphicon-chevron-right"></span> #向右翻
  25. </a>
  26. </div>
  27. <script src="{% static 'js/jquery.min.js' %}"></script> #要有JS代码才能实现轮播图
  28. <script src="{% static 'js/bootstrap.min.js' %}"></script>
  29. <script type="text/javascript">

   (四)模板继承(为了避免一些网页的重复代码)

    1.复制index.html一本命令为bak.html

  1. # 在basic.html中,将个性(不相同)内容用block替代
  2. {% load static %}
  3. <!DOCTYPE html>
  4. <html lang="en">
  5. <head><meta charset="UTF-8">
  6. <title>{% block title %}{% endblock %}</title>
  7. <meta name="viewport" content="width=device-width, initial-scale=1">
  8. <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
  9. </head>
  10. <body>
  11. <div class="container">
  12. <div id="linux-carousel" class="carousel slide">
  13. <ol class="carousel-indicators">
  14. <li class="active" data-target="#linux-carousel" data-slide-to="0"></li>
  15. <li data-target="#linux-carousel" data-slide-to="1"></li>
  16. <li data-target="#linux-carousel" data-slide-to="2"></li>
  17. </ol>
  18. <div class="carousel-inner">
  19. <div class="item active">
  20. <a href="http://www.sogou.com" target="_blank">
  21. <img src="{% static 'imgs/first.jpg' %}"> #图片放在polls下static目录的imgs目录中
  22. </a>
  23. </div>
  24. <div class="item">
  25. <img src="{% static 'imgs/second.jpg' %}">
  26. </div>
  27. <div class="item">
  28. <img src="{% static 'imgs/third.jpg' %}">
  29. </div>
  30. </div>
  31. <a href="#linux-carousel" data-slide="prev" class="carousel-control left"> <span class="glyphicon glyphicon-chevron-left"></span>
  32. 制作投票详情页 </a>
  33. <a href="#linux-carousel" data-slide="next" class="carousel-control right"> <span class="glyphicon glyphicon-chevron-right"></span>
  34. </a>
  35. </div>
  36. {% block content %}{% endblock %}
  37. <script src="{% static 'js/jquery.min.js' %}"></script>
  38. <script src="{% static 'js/bootstrap.min.js' %}"></script>
  39. <script type="text/javascript"></script>
  40. </body>
  41. </html>

   2.index.html

  1. # 修改index.html,把共性内容删除,个性内容写到对应的block中
  2. {% extends 'bak.html' %} #继承
  3. {% load static %}
  4. {% block title %}投票首页{% endblock %}
  5. {% block content %}
  6. <div class="content h4">
  7. <h1 class="text-center text-warning">投票首页</h1>
  8. <ol style="margin: 20px 0">
  9. {% for question in questions %}
  10. <li><a href="{% url 'detail' question.id %}" target="_blank">
  11. {{ question.question_text }} </a> {{ question.pub_date }}
  12. </li> {% endfor %}
  13. </ol>
  14. </div>
  15. {% endblock %}

十、制作a.html(第二个页面)

  (一)编辑views.py

  1. from django.shortcuts import render
  2. from .models import Question, Chioce
  3. # Create your views here.
  4. def index(request):
  5. d = Question.objects.order_by('-pub_date')
  6. return render(request,'index.html',{'d':d})
  7. def a(request,question_id):
  8. c = Question.objects.get(id=question_id)
  9. return render(request,'a.html',{'id':c})
  10. def result(request,id):
  11. return render(request,'result.html',{'id':id})

   (二)编辑a.html(取出选项)

  1. {% extends 'bak.html'%}
  2. {% load static %}
  3. {% block title%}polls{%endblock%}
  4. {% block content%}
  5. <div class="container">
  6. <h1>{{ id.id }}</h1>
  7. </div>
  8. <div class="content h4 text-warning" >
  9. <h1 class="text-center">chioce</h1>
  10. <h2>{{ id }}</h2>
  11. <form action="">
          {% csrf_token %} #安全选项
  12. {% for i in id.chioce_set.all %}
  13. <div class="radio">
  14. <label >
  15. <input type="radio" name="chioce_id" value="{{ chioce_id }}">
  16. {{ i.chioce_text }}
  17. </label>
  18. </div>
  19. {% endfor %}
  20. </form>
  21. </div>
  22. <div class="group">
  23. <input class="btn btn-primary" tpye="submit" value="submit">
  24. </div>
  25. {%endblock%}

十一、实现投票功能(数据库添加删除)

  实现数据库的增删改查。执行函数对model模型的操作(url–>views–>model)

  (一)配置urls.py

  1. from django.conf.urls import url,include
  2. from django.contrib import admin
  3. from . import views
  4.  
  5. urlpatterns = [
  6. url(r'^$', views.index,name='index'),
  7. url(r'(\d+)/$', views.a,name='a'),
  8. url(r'(\d+)/result/$', views.result,name='result'),
  9. url(r'(\d+)/vote/$', views.vote,name='vote'),
  10. ]

   (二)配置views.py

  1. from django.shortcuts import render, redirect
  2. from .models import Question, Chioce
  3. # Create your views here.
  4. def index(request):
  5. d = Question.objects.order_by('-pub_date')
  6. return render(request,'index.html',{'d':d})
  7. def a(request,question_id):
  8. c = Question.objects.get(id=question_id)
  9. return render(request,'a.html',{'id':c})
  10. def result(request,id):
  11. return render(request,'result.html',{'id':id})
  12. def vote(request,id):
  13. d = Question.objects.get(id=id) #取出问题
  14. # 当用户提交表单时,request.POST是一个字典,里面记录了与POST相关的数据
  15. # choice_id是detail.html页面中单选按钮的name,值是选项的id(value的值)
  16. chioce_id = request.POST.get('chioce_id') #取出name的值
  17. chioce = d.chioce_set.get(id=chioce_id)   #取出对用id的项
  18. chioce.votes += 1
  19. chioce.save()
  20. # 这里返回使用的不是render,因为render直接返回页面,URL不变,也就是http://x.x.x.x/polls/2/vote显示的是2号问题的投票结果,这是不合理的应该由http://x.x.x.x/polls/2/result/显示投票结果。所以使用redirect
  21. return redirect('result',id)

   (三)配置a.html

  1. {% extends 'bak.html'%}
  2. {% load static %}
  3. {% block title%}polls{%endblock%}
  4. {% block content%}
  5. <div class="container">
  6. <h1>{{ id.id }}</h1>
  7. </div>
  8. <div class="content h4 text-warning" >
  9. <h1 class="text-center">chioce</h1>
  10. <h2>{{ id }}</h2>
  11. <form action="{% url 'vote' id.id %}" method="post">
  12. {% csrf_token %}
  13. {% for i in id.chioce_set.all %}
  14. <div class="radio">
  15. <label >
  16. <input type="radio" name="chioce_id" value="{{ i.id }}">
  17. {{ i.chioce_text }}
  18. </label>
  19. </div>
  20. {% endfor %}
  21. <div class="form-group">
  22. <input class="btn btn-primary" type="submit" value="submit">
  23. </div>
  24. </form>
  25. </div>
  26.  
  27. {%endblock%}

 十二、配置result.html

  (一)views.py

  1. from django.shortcuts import render, redirect
  2. from .models import Question, Chioce
  3. # Create your views here.
  4. def index(request):
  5. d = Question.objects.order_by('-pub_date')
  6. return render(request,'index.html',{'d':d})
  7. def a(request,question_id):
  8. c = Question.objects.get(id=question_id)
  9. return render(request,'a.html',{'id':c})
  10. def result(request,id):
  11. d = Question.objects.get(id=id)
  12. return render(request,'result.html',{'id':d})
  13. def vote(request,id):
  14. d = Question.objects.get(id=id)
  15. chioce_id = request.POST.get('chioce_id')
  16. chioce = d.chioce_set.get(id=chioce_id)
  17. chioce.votes += 1
  18. chioce.save()
  19. return redirect('result',id)

   (二)配置resul.html

  1. {% extends 'bak.html'%}
  2. {% load static %}
  3. {% block title%}投票结果{%endblock%}
  4. {% block content%}
  5. <div>
  6. <h1 class="text-center">{{ id.id }}投票结果</h1>
  7. <table class="table table-striped table-hover">
  8. <thead class="bg-primary">
  9. <tr>
  10. <td colspan="2">{{ id.question_text }}</td>
  11. </tr>
  12. </thead>
  13. {% for i in id.chioce_set.all %}
  14. <tr>
  15. <td>{{ i.chioce_text }}</td>
  16. <td >{{ i.votes }}</td>
  17. </tr>
  18. {%endfor%}
  19. </table>
  20.  
  21. </div>
  22. {%endblock%}

 

版权声明:本文为zshBlos原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/zshBlos/p/14257954.html