zoukankan      html  css  js  c++  java
  • django学习笔记(4)

    Part 4: Forms and generic views

    ====> Write a simple form
    $ edit polls emplatespollsdetail.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 pollsviews.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 pollsviews.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 emplatespolls esults.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 pollsurls.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 pollsviews.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






  • 相关阅读:
    PHP学习笔记(三)
    简单的学习心得:网易云课堂Android开发第六章SQLite与ContentProvider 熊,我
    简单的学习心得:网易云课堂Android开发第三章自定义控件 熊,我
    简单的学习心得:网易云课堂Android开发第五章SharedPreferences与文件管理 熊,我
    简单的学习心得:网易云课堂Android开发第四章服务、广播与酷特性 熊,我
    本地Server发布外网Web应用(Oray实现)
    玩玩微信公众号Java版之准备
    C语言的第零次作业
    C语言博客作业02循环结构
    C语言博客作业03函数
  • 原文地址:https://www.cnblogs.com/hhh5460/p/4463262.html
Copyright © 2011-2022 走看看