django 官网实例 project:mysite, app:polls

环境: win7 + python2.7.13 +  django-1.11

1、django-admin startproject mysite 创建工程

2、cd mysite

3、python manage.py runserver 判断django是否正确启动

4、python manage.py startapp polls 创建应用

5、notepad polls/views.py 创建目录视图index

from django.http import HttpResponse

def index(request):
     return HttpResponse('Hello World! This is your first view, Please enjoy it')
6、notepad mysite/settings.py 在INSTALLED_APPS添加'polls', 不要忘记逗号

7、notepad mysite/urls.py

from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^polls/', include('polls.urls')),
]
8、notepad polls/urls.py 创建并管理app的路由

from django.conf.urls import url
from . import views

urlpatterns = [
     url(r'^$', views.index, name='index'),
]

9、python manage.py runserver  并访问127.0.0.1:8000/polls/ 查看结果


10 、notepad polls/model.py 为app添加定义模型

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import datetime

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

# Create your models here.

class Question(models.Model):
	question_text = models.CharField(max_length=200)  # 话题内容
	pub_date = models.DateTimeField('date published') # 话题时间
	
	def was_published_recently(self):
		return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
	
	def __unicode__(self): # python manage.py shell
		return self.question_text


class Choice(models.Model):
	question = models.ForeignKey(Question, on_delete=models.CASCADE) # 话题
	choice_text = models.CharField(max_length=200) # 选择项
	votes = models.IntegerField(default=0) # 投票数
	
	def __unicode__(self):
		return self.choice_text
11、python manage.py makemigrations  # 查看工程中模型变动情况,是否新增模型或模型新增属性等 ,需要注意的是,数据库数据未改变

       python manage.py sqlmigrations      # 使用类sql语句表达数据库的变动情况,需要注意的是,数据库数据未改变

       python manage.py migrate               # 将上述模型改变引起的数据库异动,提交给数据库,需要注意的是,数据库数据已经改变 

       python manage.py createsuperuser # 创建超级用户,查看后台程序

       python manage.py runserver 并访问 127.0.0.1:8000/admin,查看后台情况。由于此时应用虽被安装,但是应用模型并未注册,故无法看到应用情况

12、notepad polls/admin.py  # 注册应用模型

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.contrib import admin
from .models import Question, Choice

# Register your models here.

admin.site.register(Question) # 注册Question
admin.site.register(Choice)   # 注册Choice

13、python manage.py shell  # 进入django shell,插入编辑应用模型

       import django 

       django.setup()                 # 启动django

       from poll.models import Question, Choice

       from django.utils import timezone

      Question.objects,all()

      q = Question(question_text='How old are you?', pub_date=timezont.now())

      q.id q.question_text q.pub_date # 查询数据

      q.save() # 保存数据,持久化到数据库


14、notepad polls/views.py  # 为应用模型添加其余视图函数

def detail(request, question_id):
    return HttpResponse("You're looking at question %s." % question_id)

def results(request, question_id):
    response = "You're looking at the results of question %s."
    return HttpResponse(response % question_id)

def vote(request, question_id):
    return HttpResponse("You're voting on question %s." % question_id)
15、notepad polls/urls.py # 为应用模型完善视图路由

    url(r'^(?P[0-9]+)/$', views.detail, name='detail'),  # url函数,regex:正则表达式,view:视图函数, kwargs:额外参数(可选), name:路由名称(可选
    url(r'^(?P[0-9]+)/results/$', views.results, name='results'),
    url(r'^(?P[0-9]+)/vote/$', views.vote, name='vote'),
16、 python manage.py runserver 测试应用视图


17、修改模型视图函数,渲染html

from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from django.template import loader
from .models import Question
def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]   # Question查询倒叙并曲前5个
    template = loader.get_template('polls/index.html')
    context = {
        'latest_question_list': latest_question_list,    # 渲染列表
    }
    return HttpResponse(template.render(context, request))
def detail(request, question_id):
	try:
		question = Question.objects.get(pk=question_id)
	except Question.DoesNotExist:
		raise Http404("Question does not exist")
	return render(request, 'polls/detail.html', {'question': question}) # 比较render和HttpResponse
def results(request, question_id):
	question = get_object_or_404(Question, pk=question_id)             # 比较get_object_or_404 和 details函数中的try、except
	return render(request, 'polls/results.html', {'question': question})
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': "You didn't select a choice.",
		})
	else:
		selected_choice.votes += 1
		selected_choice.save()  # 数据保存,持久化
		
		return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))  # 重定向

17、为应用添加html前端页面

       notepad polls/templates/polls/index.html

{% if latest_question_list %}
    
{% else %}
    

No polls are available.

{% endif %}
      notepad polls/templates/polls/detail.html

{{ question.question_text }}

{% if error_message %}

{{ error_message }}

{% endif %}
{% csrf_token %} {% for choice in question.choice_set.all %}
{% endfor %}
     notepad polls/templates/polls/results.html

{{ question.question_text }}

    {% for choice in question.choice_set.all %}
  • {{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}
  • {% endfor %}
Vote again?
18、python manage.py runserver 查看测试情况


19、使用django模型的通用视图ListView、DetailView,简化代码

      notepad polls/views.py 

class IndexView(generic.ListView):
	template_name = 'polls/index.html'            # 模版名称
	context_object_name = 'latest_question_list'  # html中待渲染的变量
	
	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'

20、修改应用路由

      notepad polls/urls.py 

# -*- coding: utf-8 -*-

from django.conf.urls import url

from . import views

app_name = 'polls'      # app命名空间,html可直接使用 url 'polls:index' 访问inde视图,对于detail、results、vote同理

urlpatterns = [
	url(r'^$', views.IndexView.as_view(), name='index'),
	url(r'^(?P[0-9]+)/$', views.DetailView.as_view(), name='detail'),
	url(r'^(?P[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),
	url(r'^(?P[0-9]+)/vote/$', views.vote, name='vote'),
]

21、python manage.py runserver 测试

你可能感兴趣的:(Django)