您的位置:首页 > 编程语言 > Go语言

Django入门笔记【四】

2015-06-24 15:54 513 查看
入门笔记翻译整理自:https://docs.djangoproject.com/en/1.8/

*该笔记将使用一个关于投票网络应用(poll application)的例子来阐述Django的用法。

表单和通用视图(Forms&Generic Views)

1. 简单的表单

修改detail.html中的代码,使之含有<form>元素:

# 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>


以上代码:首先,为选项生成了radio按钮;其次,当你创建数据服务端(data server-side)的表单时,要始终使用method="post";然后,forloop.counter对循环进行计数;最后,由于使用了POST方法,我们需要关心跨站请求伪造(Cross Site Request Forgeries),不过Django提供了对此的保护机制。

我们在入门基础【三】中创建了如下代码:

# polls/urls.py

url(r'^(?P<question_id>[0-9]+/vote/$', views.vote, name='vote'),


向polls/views.py中添加如下代码:

# 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.vote += 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,)))


当有人在问题下投票后,vote()视图会重新定向至结果页面,该页面视图如下:

# 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})


现在,创建polls/results.html模板:

# 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>


2. 使用通用视图

注意到,detail()和results()视图很简单,并且冗余。index()视图也很相似。

这些视图代表了一种常见情形:根据URL中的被传递参数,从数据库中获取数据,载入模板,返回渲染后的模板。对于此类情形,可以使用Django提供的通用视图系统。

为了使用通用视图进行代码简化,我们需要进行以下改变:

1.转换URLconf;2.删除陈旧不必要的视图;3.引入基于通用视图的新视图

3. 修改URLconf

# polls/urls.py

from django.conf.urls import url

from . import views

ulrpatterns = [
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'),
]


注意第二和第三个模式从question_id变成了pk。

4. 修改Views

# 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


-- The End --
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: