django2.0基础

一.安装与项目的创建

1.安装

  pip install django

2.查看版本

  python -m django --version

3.创建项目

  django-admin startproject mysite

    manage.py 实用的与django项目进行交互的命令行工具
    mysite 项目中的实际python包
    mysite/__init__.py 空文件,表示这是一个python包
    mysite/settings.py 此项目的配置文件
    mysite/urls.py url声明文件
    mysite/wsgi.py wsgi服务器的配置文件

4.启动开发模式下的服务器

  python manage.py runserver 0.0.0.0:8000

    浏览器访问:http://127.0.0.1:8000/

5.创建应用

  在manage.py的同级目录下执行:

    python manage.py startapp molin

6.第一个视图文件

polls/views.py

#_*_coding:utf8_*_
from django.shortcuts import HttpResponse
def index(request):
    return HttpResponse("你好,欢迎来到投票系统的主页")

7.配置URL

  新增polls/urls.py文件

#_*_coding:utf8_*_
from django.urls import path
from . import views
urlpatterns = [
    path(‘‘, views.index, name=‘index‘),
]

8.将polls/urls.py引入到mysite/urls.py文件中, 因为所有的url配置入口都是源于mysite/urls.py

  mysite/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path(‘polls/‘, include(‘polls.urls‘)),
    path(‘admin/‘, admin.site.urls),
]

当浏览器访问 http://127.0.0.1:8000/polls/ 时,匹配到url规则path(‘polls/‘, include(‘polls.urls‘)), 然后读到polls/urls.py的配置:path(‘‘, views.index, name=‘index‘), 从而去执行polls/views.py的index方法

二.模型与数据库的交互

1.数据库的设置

  打开mysite/settings.py,可看到默认情况下,django使用的是sqlite3数据库

DATABASES = {
    ‘default‘: {
        ‘ENGINE‘: ‘django.db.backends.sqlite3‘,
        ‘NAME‘: os.path.join(BASE_DIR, ‘db.sqlite3‘),
    }
}

有些应用要求我们必须至少要有一个数据库,如,django的后台,因此,让我们先来执行以下命令: $ python manage.py migrate

  将django激活的应用所需的数据表创建好

2.创建模型

  polls/models.py

#_*_coding:utf8_*_

from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField(‘date published‘) 

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

类中的每个属性映射为一个字段,并标识了这些字段的类型

3.激活模型

  mysite/settings.py

INSTALLED_APPS = [
    ‘polls.apps.PollsConfig‘,
    # ...
]

4.生成迁移

  $ python manage.py makemigrations polls

  自动生成了polls/migrations/0001_initial.py文件,现在还没有真正创建数据表,需要再执行数据迁移才能生成数据表

  执行迁移:$ python manage.py migrate

5.让django的命令行交互更友好

  polls/models.py

from django.db import models

class Question(models.Model):
    # ...
    def __str__(self):
        return self.question_text

class Choice(models.Model):
    # ...
    def __str__(self):
        return self.choice_text

__str__()函数将会返回我们定义好的数据格式。此外,我们还可以在models中添加自定义方法:

import datetime

from django.db import models
from django.utils import timezone

class Question(models.Model):
    # ...
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

6.进入交互模式对数据库进行操作

  $ python manage.py shell

In [1]: from polls.models import Question, Choice

In [2]: Question.objects.all() # 获取所有问题
Out[2]: <QuerySet [<Question: 问题2>]>

In [3]: Question.objects.filter(id=1) # 获取id为1的数据
Out[3]: <QuerySet [<Question: 问题2>]>

In [8]: Question.objects.filter(question_text__startswith=‘问题‘) # 获取内容包含‘问题‘的数据
Out[8]: <QuerySet [<Question: 问题2>]>

In [9]: from django.utils import timezone

In [10]: current_year = timezone.now().year

In [11]: Question.objects.get(pub_date__year=current_year)
Out[11]: <Question: 问题2>

In [12]: Question.objects.get(id=2) # 当获取的数据不存在时,会报以下错误
---------------------------------------------------------------------------
DoesNotExist                              Traceback (most recent call last)
<ipython-input-12-75091ca84516> in <module>()
----> 1 Question.objects.get(id=2)

In [13]: Question.objects.get(pk=1)
Out[13]: <Question: 问题2>

In [14]: q = Question.objects.get(pk=1)

In [15]: q.was_published_recently() # 调用自定义的方法
Out[15]: True

In [16]: q = Question.objects.get(pk=1)

In [17]: q.choice_set.all()
Out[17]: <QuerySet []>
In [19]: q.choice_set.create(choice_text=‘选项1‘, votes=0)
Out[19]: <Choice: 选项1>

In [20]: q.choice_set.create(choice_text=‘选项2‘, votes=0)
Out[20]: <Choice: 选项2>

In [21]: c = q.choice_set.create(choice_text=‘选项3‘, votes=0)

In [22]: c.question
Out[22]: <Question: 问题2>

In [23]: q.choice_set.all()
Out[23]: <QuerySet [<Choice: 选项1>, <Choice: 选项2>, <Choice: 选项3>]>

In [24]: q.choice_set.count()
Out[24]: 3
In [25]: Choice.objects.filter(question__pub_date__year=current_year)
Out[25]: <QuerySet [<Choice: 选项1>, <Choice: 选项2>, <Choice: 选项3>]>

In [26]: c = q.choice_set.filter(choice_text__startswith=‘选项3‘)

In [27]: c.delete()
Out[27]: <bound method QuerySet.delete of <QuerySet [<Choice: 选项3>]>>

In [29]: Choice.objects.filter(question__pub_date__year=current_year)
Out[29]: <QuerySet [<Choice: 选项1>, <Choice: 选项2>]>

7.创建后台管理员   

django自带了一个管理后台,我们只需创建一个管理员用户即可使用
创建一个后台管理员用户: $ python manage.py createsuperuser

8.引入模型

  polls/admin.py

#_*_coding:utf8_*_
from django.contrib import admin
from .models import Question
admin.site.register(Question)

登陆后台可以对模型进行操作

三.视图views和模板template的操作

1.django的视图用于处理url请求,并将响应的数据传递到模板,最终浏览器将模板数据进行渲染显示,用户就得到了想要的结果

  增加视图:polls/views.py

#_*_coding:utf8_*_
from django.shortcuts import HttpResponse
def index(request):
    return HttpResponse("你好,欢迎来到投票系统的主页")

def detail(request, question_id):
    return HttpResponse(‘你正在查看问题%s‘ % question_id)

def results(request, question_id):
    response = ‘你正在查看问题%s的结果‘
    return HttpResponse(response % question_id)

def vote(request, question_id):
    return HttpResponse(‘你正在给问题%s投票‘ % question_id)

  配置url:polls/urls.py

#_*_coding:utf8_*_
from django.urls import path
from . import views
urlpatterns = [
    # /polls/
    path(‘‘, views.index, name=‘index‘),
    # /polls/1/
    path(‘<int:question_id>/‘, views.detail, name=‘detail‘),
    # /polls/1/results/
    path(‘<int:question_id>/results/‘, views.results, name=‘results‘),
    # /polls/1/vote/
    path(‘<int:question_id>/vote/‘, views.vote, name=‘vote‘),
]

2.通过视图直接返回的数据,显示格式很单一,要想显示丰富的数据形式,就需要引用模板,用独立的模板文件来呈现内容。

  新增模板:polls/templates/polls/index.html

{% if latest_question_list %}
    <ul>
    {% for question in latest_question_list %}
    <li><a href="/polls/{{question.id}}/">{{question.question_text}}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>问题为空</p>
{% endif %}

  修改视图: polls/views.py 传递变量给模板

#_*_coding:utf8_*_
from django.shortcuts import HttpResponse
from django.template import loader
from .models import Question
def index(request):
    latest_question_list = Question.objects.order_by(‘-pub_date‘)[:5]
    template = loader.get_template(‘polls/index.html‘)
    context = {‘latest_question_list‘: latest_question_list}
    return HttpResponse(template.render(context, request))

开发中,直接使用render()即可,尽可能精简代码

from django.shortcuts import render
from .models import Question
def index(request):
    latest_question_list = Question.objects.order_by(‘-pub_date‘)[:5]
    context = {‘latest_question_list‘: latest_question_list}
    return render(request, ‘polls/index.html‘, context)

详情页的展示:polls/views.py

from django.http import Http404
from django.shortcuts import render
from .models import Question
# ...
def detail(request, question_id):
    try:
        question = Question.objects.get(pk=question_id)
    except Question.DoesNotExist:
        raise Http404(‘问题不存在‘)
    return render(request, ‘polls/detail.html‘, {‘question‘: question})

404页面抛出的便捷写法:get_object_or_404()

polls/views.py

from django.shortcuts import render, get_object_or_404
from .models import Question
# ...
def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, ‘polls/detail.html‘, {‘question‘: question})

详情页输出关联数据表:

<h1>{{ question.question_text }}</h1>
<ul>
    {% for choice in question.choice_set.all %}
    <li>{{ choice.choice_text }}</li>
    {% endfor %}
</ul>

3.优化

  去掉url的硬编码格式

<li><a href="{% url ‘detail‘ question.id %}">{{question.question_text}}</a></li>

  修改url配置 

  将polls/urls.py的详情页url由:path(‘<int:question_id>/‘, views.detail, name=‘detail‘)改为:

    path(‘specifics/<int:question_id>/‘, views.detail, name=‘detail‘)

    此时,index.html的url会自动由 http://127.0.0.1:8000/polls/1/ 转为 http://127.0.0.1:8000/polls/specifics/1/

4.一个项目中多个应用的区分需要使用命名空间

#_*_coding:utf8_*_
from django.urls import path
from . import views
app_name = ‘polls‘
urlpatterns = [
    path(‘‘, views.index, name=‘index‘),
    path(‘<int:question_id>/‘, views.detail, name=‘detail‘),
    path(‘<int:question_id>/results/‘, views.results, name=‘results‘),
    path(‘<int:question_id>/vote/‘, views.vote, name=‘vote‘),
]

将index.html的url生成代码加上命名空间:

<li><a href="{% url ‘polls:detail‘ question.id %}">{{question.question_text}}</a></li>

四.在前台进行投票操作

1.构建一个简单的表单提交页

  polls/templates/polls/detail.html

<h1>{{ question.question_text }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{%url ‘polls:vote‘ question.id %}" method="post">
    {% csrf_token %}
    {% for choice in question.choice_set.all %}
    <input id="choice{{ forloop.counter }}" type="radio" name="choice" value="{{ choice.id }}">
    <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
    {% endfor %}
    <br />
    <input type="submit" name="" id="" value="投票" />
</form>

代码解析:

  form表单提交的url为{%url ‘polls:vote‘ question.id %}, 即表示访问polls/views.py的vote方法,并携带问题id作为参数。

  将问题的相关选项遍历,以单选框显示

  form表单用post方式提交数据

配置url: polls/urls.py

path(‘<int:question_id>/vote/‘, views.vote, name=‘vote‘),

2.视图层处理提交结果

  polls/views.py

from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from .models import Question, Choice
# ...
def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST[‘choice‘])
    except (KeyError, Choice.DoesNotExist):
        return render(request, ‘polls/detail.html‘, {
            ‘question‘: question,
            ‘error_message‘: "必须选择一个选项",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse(‘polls:results‘, args=(question.id,)))

代码解析:

request.POST[‘choice‘]接收表单页面提交的数据

将投票次数加1,并更新数据库

3.显示投票结果

  polls/views.py

from django.shortcuts import render, get_object_or_404
# ...
def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, ‘polls/results.html‘, {‘question‘: question})

  results.html

<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }} -- {{choice.votes}}</li>
{% endfor %}
</ul>

<a href="{% url ‘polls:detail‘ question.id %}">再投一次?</a>

4.优化url和view写法

  将主键id代替question_id
  polls/urls.py

#_*_coding:utf8_*_
from django.urls import path
from . import views
app_name = ‘polls‘
urlpatterns = [
    path(‘‘, views.IndexView.as_view(), name=‘index‘),
    path(‘<int:pk>/‘, views.DetailView.as_view(), name=‘detail‘),
    path(‘<int:pk>/results/‘, views.ResultsView.as_view(), name=‘results‘),
    path(‘<int:question_id>/vote/‘, views.vote, name=‘vote‘),
]

使用<pk>代替<question_id>会更加灵活,<pd>代表主键

相应的视图也需要修改成另一种写法,vote方法保持原样,用于比较两种写法的不同

polls/views.py

#_*_coding:utf8_*_
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views import generic
from .models import Question, Choice

class IndexView(generic.ListView):
    template_name = ‘polls/index.html‘
    context_object_name = ‘latest_question_list‘

    def get_queryset(self):
        return Question.objects.order_by(‘-pub_date‘)[:5]

class DetailView(generic.DetailView):
    model = Question
    template_name = ‘polls/detail.html‘

class ResultsView(generic.DetailView):
    model = Question
    template_name = ‘polls/results.html‘

def vote(request, question_id):
    # ...

  




原文地址:https://www.cnblogs.com/feiyumo/p/8377725.html

时间: 2024-08-30 10:57:00

django2.0基础的相关文章

Python3+Django2.0基础入门demo

 1.安装Python3环境 [root@openshift ~]# cat /etc/redhat-release CentOS Linux release 7.4.1708 (Core) 默认为Python2.7,需要安装Python3 [root@openshift ~]#wget https://repo.continuum.io/archive/Anaconda3-5.0.1-Linux-x86_64.sh [root@openshift ~]# yum install bzip2 [

Django2.0.1在线教育零基础到上线教程(一)

网上这么多关于这个课程的博客,为什么还需要我自己去写一遍? 我希望你看到这篇博客,也能照我这样去写一遍博客   因为这个课程反反复复学习了几遍 都没有从头到尾完整学习过一遍 . 我想通过博客去督促以及记录学习的进度! 废话不多说, 开始第一章吧! 坦白说,这个项目坑还是挺多的吧 配置环境: Python3.x + Django2.0.1 对应仓库Mxonline3 课程介绍: 第一章:项目介绍和课程介绍 Django是一个Python中Web开发的主流框架,被许多大型公司使用,如Google,豆

0基础学C语言:C语言视频教程免费分享!

C语言是一种通用的.过程式的编程语言,广泛用于系统与应用软件的开发.作为计算机编程的基础语言,长期以来它一直是编程爱好者追捧而又比较难学的语言.C语言是一种计算机程序设计语言,它既具有高级语言的特点,又具有汇编语言的特点. 很多初学者在学习C语言的时候,如果有适合自己的视频教程,学习起来就会事半功倍.今天在这里给大家分享一个0基础学习C语言的视频教程,需要的朋友可以看看,作为参考! 课程部分截图: 百度云盘下载:http://pan.baidu.com/s/1jIbtWEi 密码:npd9

华为0基础——名字的美丽度

值得注意:对于每一个名字来说:名字的美丽度=26*字母个数最多的+25*字母个数其次的+24*字母个数再其次的-- 源程序: #include<iostream> #include<string> using namespace std; const int M=50; int main() { int n,i,j,k,len; int beauti[M]={0}; int t; cin>>n; char a[M][30]; for(i=0;i<n;i++) ci

React Native 从零到高级- 0基础学习路线

React Native QQ交流群(美团,饿了么,阿里的大神都在里面):576089067 React Native  从0 基础到高级 视频教程正在重录中,要了解最新进度可以关注菜鸟窝微信公众号(下图),旧版视频教程可以点击这里在线学习 学习路线(文章版),江清清老师出品,点击这里关注江清清 ,同时可以关注一下他的课程 基础入门:1.React Native For Android环境配置以及第一个实例2.React Native开发IDE安装及配置3.React Native应用设备运行(

【转】Android 工程在4.0基础上混淆

Android现在对安全方面要求比较高了,我今天要做的对apk进行混淆,用所有的第三方工具都不能反编译,作者的知识产权得到保障了,是不是碉堡了. 一,首先说明我这是在4.0基础上进行的. 先看看project.properties 这个文件. # This file is automatically generated by Android Tools. # Do not modify this file -- YOUR CHANGES WILL BE ERASED! # # This file

Zabbix 3.0 基础介绍 [一]

Zabbix 3.0 基础介绍 [一] zabbix 一.Zabbix介绍 zabbix 简介   Zabbix 是一个高度集成的网络监控解决方案,可以提供企业级的开源分布式监控解决方案,由一个国外的团队持续维护更新,软件可以自由下载使用,运作团队靠提供收费的技术支持赢利   zabbix是一个基于Web界面的,提供分布式系统监控以及网络监视功能的企业级的开源解决方案.   zabbix能监视各种网络参数,保证服务器系统的安全运营,并提供灵活的通知机制以让系统管理员快速定位/解决存在的各种问题

在Eclipse中使用JUnit4进行单元測试(0基础篇)

本文绝大部分内容引自这篇文章: http://www.devx.com/Java/Article/31983/0/page/1 我们在编写大型程序的时候,须要写成千上万个方法或函数,这些函数的功能可能非常强大,但我们在程序中仅仅用到该函数的一小部分功能,而且经过调试能够确定,这一小部分功能是正确的.可是,我们同一时候应该确保每个函数都全然正确,由于假设我们今后假设对程序进行扩展,用到了某个函数的其它功能,而这个功能有bug的话,那绝对是一件非常郁闷的事情.所以说,每编写完一个函数之后,都应该对这

Java 入门课程视频实战-0基础 上线了,猜拳游戏,ATM实战,欢迎围观

Java 入门课程视频实战-0基础 已经上传完了.欢迎小伙伴们过来围观 直接进入: http://edu.csdn.net/course/detail/196 课程文件夹例如以下: 1 初识Java  19:08 2 熟悉Eclipse开发工具  12:42 3 Java语言基础  17:39 4 流程控制  14:53 5 数组  14:44 6 字符串  34:32 7 类和对象  29:30 8 猜拳游戏  33:39 9 模拟银行柜员机程序  36:35 10 退休金结算程序  本课程由