我想用UpdateView替换Djangos Poll Tutorial中的DetailView。不幸的是,它显示的是民意调查清单而不是选择+投票清单。
我的模特民意调查,选择没有变化。投票视图的模板保持最简单:
<h1>{{ poll }}</h1>
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Vote" />
</form>
如何让表单显示特定的投票和选项列表,如教程中详细视图的手动构建形式所示:
<form action="{% url 'polls:vote' poll.id %}" method="post">
{% csrf_token %}
{% for choice in poll.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>
答案 0 :(得分:0)
使用ModelChoiceField
和RadioSelect
窗口小部件:
class ChoicesForm(forms.Form):
choice = forms.ModelChoiceField(queryset=Choice.objects.none(),
widget=forms.RadioSelect,
required=True,
empty_label=None)
def __init__(self, *args, **kwargs):
poll = kwargs.pop('poll')
super(ChoicesForm, self).__init__(*args, **kwargs)
self.fields['choice'].queryset = poll.choice_set.all()
form = ChoicesForm(poll=poll)