首页 > 解决方案 > 教程:请帮助重写课程表格?

问题描述

我无法将 mysite/polls 表单重写为类。每次都会遇到不同的错误。

    <!-- detail.html -->
    <form action="" method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="Vote">
    </form>
# forms.py:
from django import forms
from .models import Choice

class VoteForm(forms.ModelForm):
    choices = [(ch.pk, ch.choice_text) for ch in Choice.objects.filter(pk=pk)]
    choices = tuple(choices)
    choice_text = forms.ChoiceField(widget=forms.RadioSelect(choices=choices))
    class Meta:
        model = Choice
        fields = ['choice_text']
# views.py#
class DetailView(generic.FormView, generic.DetaildView):
    model = Question
    template_name = 'polls/detail.html'
    form_class = VoteForm
    def get_queryset(self):
        """
        Excludes any questions that aren't published yet.
        """
        return Question.objects.filter(pub_date__lte=timezone.now())

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        #context["pk"] = self.pk
        #context["form"] = VoteForm()
        return context

    #def get(self, request, *args, **kwargs):
        #form = VoteForm(pk=kwargs['pk'])
        #return super().get(self, request, *args, **kwargs)

你如何将它们绑定在一起?如何获取表单中的question_id(pk),如何与详细视图混合,如何正确检查验证此表单?

我很困惑。可能吗?

标签: djangodjango-modelsdjango-viewsdjango-formsdjango-templates

解决方案


推荐阅读