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.  

最新文章

  1. MySQL 的相关语句(增删改查)(SQLyog软件实现)
  2. [MongDB] 主从架构--官方极力不推荐
  3. AttributeError: type object &#39;_io.StringIO&#39; has no attribute &#39;StringIO&#39;
  4. 【转】MySQL性能优化的21个最佳实践
  5. 建立开发板与PC机之间的nfs服务器
  6. LNK1179 无效或损坏的文件: 重复的 COMDAT“_IID_IDispatchEx”
  7. InputStream和Reader区别
  8. JSP的隐式对象
  9. sharepoint 2013 更改搜索server组态
  10. Android Studio 没有assets目录的问题
  11. Singleton模式(Singleton创建类型)c#简单的例子
  12. Docker镜像导致centos-root根分区容量爆满
  13. lr 中cookie的解释与用法
  14. OpenStack--ntp组件时间同步服务
  15. coding基本功实践
  16. jdk环境变量配置改变不生效的问题
  17. Ajax请求中的async:false/true的作用[转]
  18. MapRedcue的demo(协同过滤)
  19. windows安装使用docker
  20. Python中 __init__的通俗解释?附修饰器contextmanager的理解

热门文章

  1. 27.Qt时钟
  2. Java io 操作
  3. Oracle学习系类篇(三)
  4. Caffe_Scale层解析
  5. C++利用函数模板得到数组的长度
  6. C#基础篇之语言和框架介绍
  7. Unity 声音播放不受Time.scale为0的影响
  8. 12 个最佳 GNOME(GTK)主题
  9. idea编写Swing程序中文乱码的解决办法
  10. ios兼容 input输入时弹出键盘框 页面整体上移键盘框消失后在ios上页面不能回弹的问题