Frist Django app-4. Improved View and fristdjango

Source: Internet
Author: User

Frist Django app-4. Improved View and fristdjango

The previous article has completed the basic functions of polls. Next, we will improve the remaining vote functions and use generic views to improve the view processing of requests. Contains simple use of forms and frontend and backend parameter transfer.

Directory
  • Vote: Improves the voting Function
  • Generic views: Improves views. py
Vote

Edit detail.html to add the voting Function


 
  • A form is added and submitted using post. The submitted address is polls: vote, which represents an address, for example, http: // 127.0.0.1: 8000/polls/4/vote /.
  • In this case, form submission is involved. Add {% csrf_token %} to prevent csrf attacks. The principle is that the tokens used each time are inconsistent, so that requests cannot be forged.
  • Forloop. counter is the counter of the for loop.

Edit views. py to add the voting function. Pay attention to introduce related classes.

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 did`t select choice.",        })    else:        selected_choice.votes += 1        selected_choice.save()        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
Request. POST ['choice'] obtains the parameters passed by the foreground from the post request, request. POST is a dictionary, the key is the parameter name, and the value is the parameter value. If the file is a get request, it is the request. GET
Return HttpResponseRedirect (reverse ('polls: results', args = (question. (id,) after the vote is successful, the page is redirected to prevent the user from submitting the form repeatedly after using the browser's rollback function.

So far, the function has been completed. You can test it, start the server, and then test related functions.
Generic views

For many web apps, the method of displaying content is similar, for example, viewing a list and a specific content, for this reason, Django provides generic views-Django explains what is fast and convenient development!

Use generic views to rewrite views. py

from django.shortcuts import render, get_object_or_404from django.http import HttpResponse, Http404, HttpResponseRedirectfrom models import Question, Choicefrom django.views import genericfrom django.core.urlresolvers import reverse# Create your views here.class IndexView(generic.ListView):    template_name = 'polls/index.html'    context_object_name = 'latest_question_list'    def get_queryset(self):        return Question.objects.order_by('-publ_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):    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 did`t select choice.",        })    else:        selected_choice.votes += 1        selected_choice.save()        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

We have rewritten index, detail, and result, and used ListView and DetailView.

IndexView describes the get_quesryset method to implement our own logic. It sets the template page and the returned parameter name.

DetailView sets the model and template pages required to display detailed information.

Since generic views is used, you need to rewrite urls. py.

from django.conf.urls import urlfrom . import viewsapp_name = 'polls'urlpatterns = [    url(r'^$', views.IndexView.as_view(), name = 'index'),    url(r'^(?P<pk>[0-9]+)/detail/$', 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'),]

In order to use generic views to change the parameter name to pk, because this name is already used in the DetailView-this is the convention is better than the configuration.

 

Summary

After the entire program is basically finished, we can look back and find that there are not many codes actually written by ourselves, basically relying on Django. It can be seen that using Django to build a website quickly makes sense.

 

Complete code

Http://pan.baidu.com/s/1o8zqGhs

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.