zoukankan      html  css  js  c++  java
  • Django L4 编写你的第一个Django应用

    编写一个简单的表单

    $ cat tasks/views.py | tail -18
    
    def vote(request, question_id):
        p = get_object_or_404(Questions, 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, 'tasks/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('tasks:results', args=(p.id,)))
    
    $cat tasks/urls.py
    #!/usr/bin/env python
    #-*- coding: utf-8 -*-
    
    __author__ = 'Ye Lin'
    __date__ = '17-2-9'
    
    from django.conf.urls import url
    
    from . import views
    
    urlpatterns = [
        url(r'^$' , views.index , name='index'),
        url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
        # http://127.0.0.1:20001/tasks/1/results/
        url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
        # http://127.0.0.1:20001/tasks/1/vote/
        url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
    
    ]
    

      

       由于这种情况非常普遍,Django提供了一种叫做“generic views”的系统可以方便地进行处理。

    使用通用视图,代码少点

      改良URLconf

    #!/usr/bin/env python
    #-*- coding: utf-8 -*-
    
    __author__ = 'Ye Lin'
    __date__ = '17-2-9'
    
    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'),
    ]
    

      

    改良视图

    from django.shortcuts import render , get_object_or_404 , HttpResponseRedirect
    from django.http import Http404
    from django.http import HttpResponse
    from django.core.urlresolvers import reverse
    from django.views import generic
    # Create your views here.
    
    from .models import *
    from django.template import RequestContext, loader
    
    
    
    class IndexView(generic.ListView):
        template_name = 'tasks/index.html'
        context_object_name = 'latest_question_list'
    
        def get_queryset(self):
            """Return the last five published questions."""
            return Questions.objects.order_by('-pub_date')[:5]
    
    
    class DetailView(generic.DetailView):
        model = Questions
        template_name = 'tasks/detail.html'
    
    
    class ResultsView(generic.DetailView):
        model = Questions
        template_name = 'tasks/results.html'
    
    
    def vote(request, question_id):
        p = get_object_or_404(Questions, 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, 'tasks/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('tasks:results', args=(p.id,)))
    

      

  • 相关阅读:
    Nginx 均衡负载
    今天不知道写啥
    ios 多线程管理中的关键点
    iOS 开发中 想对于方便的MBProgressHUD
    UitableView 中原创动态高度计算
    iOS 开发中常见的错误日志处理
    设计模式之二-Proxy模式
    设计模式之一-Stratrgy模式
    core dumped问题查找以及使用gdb、QT下gdbserver使用
    ssh、scp的使用,以及shell脚本解决scp需要输入密码的问题
  • 原文地址:https://www.cnblogs.com/zsr0401/p/6385863.html
Copyright © 2011-2022 走看看