zoukankan      html  css  js  c++  java
  • Django -- Form


    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>
     {% csrf_token %} 提交表单首先要做的,用于防止跨域攻击
     {{ forloop.counter }} for标签自带的变量,统计for循环的次数
     method="post",涉及数据库改变的药用post方法

    urls.py

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

    views.py

    def vote(request, question_id):
        question = get_object_or_404(Question, pk=question_id)
        try:
            selected_choice = question.choice_set.get(pk=request.POST['choice'])
        except (KeyError, Choice.DoesNotExist):
            # Redisplay the question voting form.
            return render(request, 'polls/detail.html', {
                'question': question,
                '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=(question.id,)))
    request.POST是一个字典,键为input中的name,值为value

      HttpResponseRedirect 处理完POST请求后要返回这个,而不是普通的HTTPResponse。能够避免数据被提交两次(用户按返回键时)

    reverse 避免硬编码,会自动生成一个URL字符串
      
    KEEP LEARNING!
  • 相关阅读:
    node-sass 安装失败
    js中复制功能总结
    设置NODE_ENV=test环境变量
    js eslint语法规范错误提示代码
    npm安装node包时怎么显示安装进度
    前端面试题总结三
    5种方式将数字转成千分位
    前端面试题总结二(js原型继承)
    前端面试题总结一(js变量和函数声明提前相关)
    1109 Group Photo (25分)
  • 原文地址:https://www.cnblogs.com/roronoa-sqd/p/4916152.html
Copyright © 2011-2022 走看看