django学习笔记(4)

简介:

django学习笔记(4)

Part 4: Forms and generic views

====> Write a simple form
$ edit 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 type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
    <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>
复制代码


$ edit polls\views.py

复制代码
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse

from .models import Choice, Question
# ...
def vote(request, question_id):
    p = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = p.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'polls/detail.html', {
            'question': p,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
复制代码


$ edit polls\views.py

from django.shortcuts import get_object_or_404, render


def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/results.html', {'question': question})


$ edit polls\templates\polls\results.html

复制代码
<h1>{{ question.question_text }}</h1>

<ul>
{% for choice in question.choice_set.all %}
    <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>

<a href="{% url 'polls:detail' question.id %}">Vote again?</a>
复制代码

 




====> Use generic views: Less code is better

$ edit polls\urls.py

复制代码
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
    url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),
    url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]
复制代码


$ edit polls\views.py

复制代码
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic

from .models import Choice, Question


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

    def get_queryset(self):
        """Return the last five published questions."""
        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):
    ... # same as above
复制代码

 





本文转自罗兵博客园博客,原文链接:http://www.cnblogs.com/hhh5460/p/4463262.html,如需转载请自行联系原作者

相关文章
|
5月前
|
Python
基于Django的Python应用—学习笔记—功能完善
基于Django的Python应用—学习笔记—功能完善
|
5月前
|
存储 数据库 数据安全/隐私保护
基于Django的Python应用——学习笔记
基于Django的Python应用——学习笔记
|
安全 中间件 开发者
【Django学习笔记 - 9】:装饰器在类视图中的使用、中间件(开发中间件)、知识点小补充(子应用的集中管理)
【Django学习笔记 - 9】:装饰器在类视图中的使用、中间件(开发中间件)、知识点小补充(子应用的集中管理)
358 3
【Django学习笔记 - 9】:装饰器在类视图中的使用、中间件(开发中间件)、知识点小补充(子应用的集中管理)
|
数据库 数据安全/隐私保护 Python
【Django学习笔记 - 19】:认证、自定义认证、权限、限流
【Django学习笔记 - 19】:认证、自定义认证、权限、限流
266 0
【Django学习笔记 - 19】:认证、自定义认证、权限、限流
|
缓存 前端开发 数据库
【Django学习笔记 - 18】:drf请求响应简介、基类(APIView、GenericAPIView)、mixin扩展类与三级视图、视图集与路由2
【Django学习笔记 - 18】:drf请求响应简介、基类(APIView、GenericAPIView)、mixin扩展类与三级视图、视图集与路由
156 0
【Django学习笔记 - 18】:drf请求响应简介、基类(APIView、GenericAPIView)、mixin扩展类与三级视图、视图集与路由2
|
XML JSON 前端开发
【Django学习笔记 - 18】:drf请求响应简介、基类(APIView、GenericAPIView)、mixin扩展类与三级视图、视图集与路由
【Django学习笔记 - 18】:drf请求响应简介、基类(APIView、GenericAPIView)、mixin扩展类与三级视图、视图集与路由
203 0
【Django学习笔记 - 18】:drf请求响应简介、基类(APIView、GenericAPIView)、mixin扩展类与三级视图、视图集与路由
|
XML JSON 前端开发
【Django学习笔记 - 17】:序列化和反序列化(restful接口小案例、DRF的工程搭建、序列化器与序列化、验证、保存)
【Django学习笔记 - 17】:序列化和反序列化(restful接口小案例、DRF的工程搭建、序列化器与序列化、验证、保存)
516 0
【Django学习笔记 - 17】:序列化和反序列化(restful接口小案例、DRF的工程搭建、序列化器与序列化、验证、保存)
|
JSON 前端开发 JavaScript
【Django学习笔记 - 16】:DRF概述、Web应用模式(前后端分离简介)
【Django学习笔记 - 16】:DRF概述、Web应用模式(前后端分离简介)
286 0
【Django学习笔记 - 16】:DRF概述、Web应用模式(前后端分离简介)
|
Python
【Django学习笔记 - 15】:admin站点编辑(关联对象在列表页中添加,编辑页调整、图片设置)2
【Django学习笔记 - 15】:admin站点编辑(关联对象在列表页中添加,编辑页调整、图片设置)
【Django学习笔记 - 15】:admin站点编辑(关联对象在列表页中添加,编辑页调整、图片设置)2