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!
  • 相关阅读:
    sql server中使用链接服务器访问oracle数据库
    biztalk中使用信封(Envelope)消息
    EMS SQL Manager 2007 for MySQL发布
    MySQL Connector/NET
    Silverlight相关资源
    ADO.NET嵌套数据绑定
    收到网上订得书了,开始充电...
    几个.net下的ajax框架
    Visual Studio 2008 Beta 2 初步体验
    .Net Remoting常用部署结构
  • 原文地址:https://www.cnblogs.com/roronoa-sqd/p/4916152.html
Copyright © 2011-2022 走看看