【问题标题】:How to increase a value (pushing a button) in a html django template using a for loop?如何使用 for 循环在 html django 模板中增加值(按下按钮)?
【发布时间】:2019-07-16 06:31:44
【问题描述】:

我实际上正在为一个学校项目编写一个提问网站。 我按照官方网站上的 django 教程的第一步,但我现在正在尝试自己改进它。

我在每个 div(在 for 循环中创建)中添加了一个“投票”按钮,我想在我的 views.vote 中增加该按钮。

一些代码会更解释。

所以这是我的 detail.html,它显示了我所有的问题以及对这个问题的选择/回答,每个选择都有一个投票按钮:

{% block content %}
    <h2>{{ question.question_text }}</h2>

    {% 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 %}
            <div class="choices">
                <label for="">{{ choice.choice_text }}</label><br>
                <p>{{ choice.votes }} vote{{ choice.votes|pluralize }}</p>
                <input type="submit" name="vote" id=""  value="Vote">
            </div>
        {% endfor %}
        <br>
    </form>
    <a href="{% url 'polls:choice' question.id %}">Add a choice</a>
{% endblock %}

这是我的views.vote,它得到了正确的问题并且(应该)获得了正确选择的“投票”值来增加:

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['vote'])
    except (KeyError, Choice.DoesNotExist):
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:detail', args=(question.id,)))

我的“投票”值在我的“选择”对象中声明如下:

class Choice(models.Model):
    votes = models.IntegerField(default=0)

实际上,当我按下“投票”按钮时,我会收到以下错误消息:

invalid literal for int() with base 10: 'Vote'

我是 django 的真正初学者,所以请善待!

【问题讨论】:

    标签: django for-loop button vote-up-buttons


    【解决方案1】:

    你的错误是:

    <input type="submit" name="vote" id=""  value="Vote">
    

    既然你正在使用

    selected_choice = question.choice_set.get(pk=request.POST['vote'])
    

    request.POST['vote'] 将返回“投票”作为结果。这是因为它获取了定义为value="Vote"&lt;input&gt; 的值,但是您的视图语句需要一个整数值。

    要解决您的问题,您需要在 value 字段中传递选项的 id,例如:

    <input type="submit" name="vote" id=""  value="{{ choice.id }}">
    

    我建议您使用button 而不是input

    <button type="submit" name="vote" id=""  value="{{ choice.id }}">Vote</button>
    

    【讨论】:

      猜你喜欢
      • 2014-09-14
      • 2019-08-30
      • 1970-01-01
      • 1970-01-01
      • 2021-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-03
      相关资源
      最近更新 更多