首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用django表单重写表单

用django表单重写表单
EN

Stack Overflow用户
提问于 2017-02-18 21:40:32
回答 1查看 208关注 0票数 1

我想重写django tutorial polls应用程序的投票表单。但我想不出如何为问题的所有选项制作一个单选列表:

代码语言:javascript
复制
{% 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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-02-21 01:39:41

经过大量的实验,这就是解决方案:

代码语言:javascript
复制
#forms.py
class VoteForm(forms.ModelForm):
    choice = forms.ModelChoiceField(queryset=None, widget=forms.RadioSelect)

    class Meta:
        model = Question
        exclude = ('question_text', 'pub_date')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['choice'].error_messages = {
            'required': 'No choice selected.',
            'invalid_choice': 'Invalid choice selected.'
        }
        instance = getattr(self, 'instance', None)
        if instance:
            self.fields['choice'].queryset = instance.choice_set
#vote.html
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/css/style.css' %}" />
<h2>{{ question.question_text }}</h2>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
{% if voted %}
<p><strong>Already voted on this question.</strong><p>
{% else %}
<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
{{ form.non_field_errors }}
<div class="fieldWrapper">
    {{ form.choice.errors }}
    {{ form.choice }}
</div>
<input type="submit" value="Vote" />
</form>
{% endif %}
<p><a href="{% url 'polls:results' question.id %}">View results?</a></p>
#views.py
class VoteView(generic.UpdateView):
template_name = 'polls/vote.html'
model = Question
form_class = VoteForm

def get_queryset(self):
    return Question.objects.filter(pub_date__lte=timezone.now()).exclude(choice__isnull=True)

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    # Check duplicate vote cookie
    cookie = self.request.COOKIES.get(cookie_name)
    if has_voted(cookie, self.object.id):
        context['voted'] = True
    return context

def get_success_url(self):
    return reverse('polls:results', args=(self.object.id,))

def form_valid(self, form):
    choice = form.cleaned_data['choice']
    choice.votes = F('votes') + 1
    choice.save()
    redirect = super().form_valid(form)

    # Set duplicate vote cookie.
    cookie = self.request.COOKIES.get(cookie_name)
    half_year = timedelta(weeks=26)
    expires = datetime.utcnow() + half_year
    if cookie and re.match(cookie_pattern, cookie):
        redirect.set_cookie(cookie_name, "{}-{}".format(cookie, self.object.id), expires=expires)
    else:
        redirect.set_cookie(cookie_name, self.object.id, expires=expires)

    return redirect
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42315879

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档