复选框为使用ModelForm的相关模型选择多个(多个选项)

时间:2018-11-10 17:09:12

标签: python django python-3.x django-models

我需要编写一个简单的应用程序,用户可以选择多个选项(多个选项),我可以这样创建内容:
models.py

from django.db import models

# Create your models here.
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    choice_limit = models.PositiveSmallIntegerField(default=1)
    add_date = models.DateTimeField('add date', auto_now_add=True)
    change_date = models.DateTimeField('change date', auto_now=True)
    question_enable = models.BooleanField('is published', default=False)

    def __str__(self):
        return self.question_text


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return "%s %s %s" % (self.question, self.choice_text, self.votes)

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'])
        some_var = request.POST.getlist('choice')
        selected_2 = Choice.objects.filter(question__in=some_var)
    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:
        for x in selected_2:
            x.votes += 1
            x.save()
        return HttpResponseRedirect("/")

模板

<form action="{% url 'vote' question.id %}" method="post">
{% csrf_token %}
    <fieldset>
    <legend>Please select one of the following</legend>
{% for choice in question.choice_set.all %}
    <input type="checkbox" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
    <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br>
{% endfor %}
        </fieldset>
<input type="submit" value="Vote">

我不知道这是Django的好方法吗?用ModelForm和通用视图编写此应用程序是否可行?我可以用其他方式验证表格吗?我尝试找到一些解决方案,但我仅发现: Django Multiple Choice Field / Checkbox Select Multiple one-to-many inline select with django admin 但是那些不能解决我的问题。我已经尝试制作一些ModelForm,但是没有任何好的结果。

0 个答案:

没有答案