1. 一个简单的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>
    • forloop.counter:表示for循环执行的次数
    • action="{% url 'polls:vote' question.id %}":指定处理post 数据的url
    • {% csrf_token %}:用于防止csrf攻击的tag,所有post的form都应该使用
  2. 处理post的代码:
    #polls/urls.py
    url(r'^(?P<question_id>\d+)/vote/$', views.vote, name='vote'), #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, 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,)))

    # polls/view.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})
    • request.POST:用于获取表单的值,同样的属性还有request.GET
    • request.POST[‘choice’]:choice是key值,不存在时引发KeyError exception
    • HttpResponseRedirect():参数是一个重定向的url\
    • reverse():返回一个url,通过使用url name避免hardcode
  3. Generic view:
    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 polls.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 告诉django自动生成的template的name
    #如果不指定默认为<app name>/<model name>_detail.html
    template_name = 'polls/detail.html' #polls/urls.py
    #注意必须用<pk>指定匹配的组名
    urlpatterns = patterns('',
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'), )
  4. 静态文件:django的STATICFILES_FINDERS setting保存了一系列finder,这些finder知道如何去查找静态文件。如AppDirectoriesFinder就会在INSTALLED_APPS包含的app的子目录下查找static目录。通常用如下存放静态文件,polls/static/polls/style.css或者polls/static/polls/images/background.gif,这样AppDirectoriesFinder可以找到,路径中第二个polls相当于静态文件的名字空间
    #polls/templates/polls/index.html
    {% load staticfiles %}
    <link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
  5. How to packaging your app:参考https://docs.djangoproject.com/en/1.7/intro/reusable-apps/
  6.  

Django(part4)的更多相关文章

  1. “全能”选手—Django 1.10文档中文版Part4

    第一部分传送门 第二部分传送门 第三部分传送门 3.2 模型和数据库Models and databases 3.2.2 查询操作making queries 3.3.8 会话sessions 2.1 ...

  2. 实战Django:官方实例Part4

    上一个part我们创建了投票的内容页,但这个页面仅仅局限于静态展示,投票的"投"字还无从体现.接下来,我们就来看一下,如何把票投起来.   19.创建表单 我们来更新模板文件pol ...

  3. django入门-表单-part4

    尊重作者的劳动,转载请注明作者及原文地址 http://www.cnblogs.com/txwsqk/p/6514113.html 完全翻译自官方文档 https://docs.djangoproje ...

  4. Django 1.10文档中文版Part4

    2.10 高级教程:如何编写可重用的apps 2.10.1 重用的概念 The Python Package Index (PyPI)有大量的现成可用的Python库.https://www.djan ...

  5. django with mysql (part-4)

    step01: write the ( views.py ) again .. vim views.py step02: configure your (urls.py) step03: check ...

  6. 实战Django:官方实例Part5

    俗话说,人非圣贤,孰能无过.在堆代码的过程中,即便是老攻城狮,也会写下一些错误的内容.俗话又说,过而能改,善莫大焉.要改,首先要知道哪里存在错误,这便是我们要对投票应用进行测试的原因.   21.撰写 ...

  7. 初步了解 Django Models

    Part1:了解主键 1.      Python和Django版本如下: E:\django>python3 -V Python 3.5.2 E:\django>python3 -m d ...

  8. Python-Django 第一个Django app

    第一个Django app   by:授客 QQ:1033553122 测试环境: Python版本:python-3.4.0.amd64 下载地址:https://www.python.org/do ...

  9. python笔记-19 javascript补充、web框架、django基础

    一.JavaScript的补充 1 正则表达式 1.1 test的使用 test 测试是否符合条件 返回true or false 1.2 exec的使用 exec 从字符串中截取匹配的字符 1.3 ...

随机推荐

  1. c++面向对象程序设计 谭浩强 第五章答案

    1: #include <iostream> using namespace std; class Student {public: void get_value() {cin>&g ...

  2. filezilla的root账户无法连接服务器解决办法

    lz一直都是用filezilla上传文件到vm虚拟机的,用的是ubuntu14.04的系统.最近自己重新搭了lamp去做thinkphp的学习,lz有两个账户,一个是kin,另外一个是root.大家都 ...

  3. extjs 与html相结合 自定义

    http://skirtlesden.com/articles/html-and-extjs-components

  4. UVa512 追踪电子表格中的单元格

    https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem& ...

  5. composer的一些操作

    版本更新 命令行下:composer self-update 设置中国镜像 composer config -g repo.packagist composer https://packagist.p ...

  6. Hua Wei 机试题目一

    一.身份证号码验证 题目描述: 我国公民的身份证号码特点如下:1. 长度为18位:2. 第1-17位只能为数字:3. 第18位可以是数字或者小写英文字母x.4. 身份证号码的第7~14位表示持有人生日 ...

  7. 软件测试中的fault,error,failure

    问题:给定两段代码,设计fault,error,failure的测试用例. fault:即引起错误的原因,类似病因. error:类似疾病引起的内部结果. failure:类似疾病引起的症状. 代码1 ...

  8. day09-1 列表,元祖的内置方法

    目录 列表类型的内置方法 作用 定义方式 方法 优先掌握 需要掌握 储存一个值or多个值 有序or无序?(有序:有索引, 无序:无索引) 可变or不可变(可变:值变id不变,不可变:值变id也变) 元 ...

  9. DOS下格式化移动硬盘

    有的时候移动硬盘出现问题,在Win下没法操作,只能到dos下格式化.以下是用Win自带的diskpart完成格式化. 1  win + r   -> cmd  进入dos 2  diskpart ...

  10. luoguP4512 【模板】多项式除法 NTT+多项式求逆+多项式除法

    Code: #include<bits/stdc++.h> #define maxn 300000 #define ll long long #define MOD 998244353 # ...