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!
  • 相关阅读:
    poj 3070 矩阵快速乘
    将数字放大显示
    hdu 火车入队 stack
    linq to Entity 数据库除了有主键还有唯一索引,是不是不能更新
    整理:C#写ActiveX, 从代码到打包到签名到发布的示例
    Java—FileOperator
    第二章-递归与分治策略
    第四章-贪心算法
    第五章-回溯法
    Linux中C程序调试、makefile
  • 原文地址:https://www.cnblogs.com/roronoa-sqd/p/4916152.html
Copyright © 2011-2022 走看看