七日Python之路--第三天(之初试Django 2-2)

时间:2022-07-22
本文章向大家介绍七日Python之路--第三天(之初试Django 2-2),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

接上文。前面(1)(2)部分已经实现浏览器访问工程项目,并且能后台管理新创建的app。

(二)第一个Django的app


(3)教你开始写Django1.6的第1个app

前面已经完成了model(M)的设置。剩下的只有view(V)和urls(C)了。Django的视图部分,由views.py 和 templates完成。

在polls中,我们将创建4个视图:

“index” 列表页 – 显示最新投票。
“detail” 投票页 – 显示一个投票的问题, 以及用户可用于投票的表单。
“results” 结果页 – 显示一个投票的结果。
投票处理 – 对用户提交一个投票表单后的处理。

现在修改 views.py 创建用于视图的函数。

dizzy@dizzy-pc:~/Python/mysite$ vim polls/views.py
from django.shortcuts import render,get_object_or_404

# Create your views here.
from django.http import HttpResponse
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    context = {'latest_poll_list':latest_poll_list}
    return render(request,'polls/index.html',context)

def detail(request,poll_id):
    poll = get_object_or_404(Poll,pk=poll_id)
    return render(request,'polls/detail.html',{'poll':poll})

def results(request,poll_id):
    return HttpResponse("you're looking at the results of poll %s." % poll_id)

def vote(request,poll_id):
    return HttpResponse("you're voting on poll %s." % poll_id)

#涉及Django的自带函数,不做深究。后面再做研究!

要想使试图能被访问,还要配置 urls.py 。mysite是整个网站的URLConf,但每个app可以有自己的URLConf,通过include的方式导入到根配置中即可。现在在polls下面新建 urls.py

from django.conf.urls import patterns,url

from polls import views

urlpatterns = patterns('',
    #ex:/polls/
    url(r'^$',views.index,name='index'),
    #ex:/polls/5/
    url(r'^(?P<poll_id>d+)/$',views.detail,name='detail'),
    #ex:/polls/5/results/
    url(r'^(?P<poll_id>d+)/results/$',views.results,name='results'),
    #ex:/polls/5/vote/
    url(r'^(?P<poll_id>d+)/vote/$',views.vote,name='vote'),
)
#url中,三个参数。正则的url,处理的函数,以及名称
#正则表达式!!!!!

然后在根 urls.py 文件中,include这个文件即可。

dizzy@dizzy-pc:~/Python/mysite$ vim mysite/urls.py
from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'mysite.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^polls/', include('polls.urls',namespace="polls")),
    url(r'^admin/', include(admin.site.urls)),
)
#有Example:两种形式。因为是元组,所以开始有“ ‘’, ”。

然后开始创建模板文件。在polls下,创建templates文件夹。下面有index.html, detail.html 两个文件。

<!-- index.html -->
{% if latest_poll_list %}
    <ul>
    {% for poll in latest_poll_list %}
        <li><a href="{% url 'polls:detail' poll_id=poll.id %}">{{ poll.question }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}

<!--detail.html-->
<h1>{{ poll.question }}</h1>
<ul>
{% for choice in poll.choice_set.all %}
    <li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>

<!-- 视图设置完毕,具体语法还要深入研究! -->
<!-- 现在重启服务, 便可看到相应视图  -->

(4)教你开始写Django1.6的第1个app

上面只是简单的实现了视图功能,并没有真正的实现投票功能。接下来就是完善功能。

#修改模板文件
dizzy@dizzy-pc:~/Python/mysite$ vim polls/templates/polls/detail.html
#需要加入form表单
<h1>{{ poll.question }}</h1>
 
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
 
<form action="{% url 'polls:vote' poll.id %}" method="post">
{% csrf_token %}
{% for choice in poll.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>

然后需要修改 views.py 中的 vote 处理函数。进行post数据的接收与处理。

# 文件 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 polls.models import Choice, Poll
# ...
def vote(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    try:
        selected_choice = p.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the poll voting form.
        return render(request, 'polls/detail.html', {
            'poll': 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,)))

在投票成功之后,让用户浏览器重定向到结果 results.html 页。

def results(request, poll_id):
    poll = get_object_or_404(Poll, pk=poll_id)
    return render(request, 'polls/results.html', {'poll': poll})

然后就需要创建模板 results.html 。

<!-- polls/templates/polls/results.html -->

<h1>{{ poll.question }}</h1>
 
<ul>
{% for choice in poll.choice_set.all %}
    <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>
 
<a href="{% url 'polls:detail' poll.id %}">Vote again?</a>

至此,重启服务就能看到单选按钮,以及submit了。


but,发现这个竟然是官网上的例子..........................Orz...................


源地址:https://docs.djangoproject.com/en/1.6/ Django1.6 官方文档 看来自己又犯二了...... 还是等着明后天的看官方文档吧!!!

--2014.7.23 16:44