为什么表单在FormView上无效?

时间:2019-06-22 12:33:50

标签: django django-forms django-templates django-views

所有字段均已填写。但是由于某种原因,它没有进入form_valid方法,而是进入了form_invalid。为什么表格无效?

forms.py

class CreditFilterForm(forms.Form):
    CURRENCY_CHOICES = (
        ('KZT', _('KZT')),
        ('USD', _('USD')),
    )

    PERIOD_CHOICES = (
        ('1', _('One year')),
        ('2', _('Two')),
        ('3', _('Three'))
    )

    sum = forms.CharField(widget=forms.NumberInput(attrs={'id': "sum", 'class':"forminput-text"}))
    currency = forms.ChoiceField(choices = CURRENCY_CHOICES, widget=forms.Select(attrs={'name': "minbeds", 'id':"currency"}))
    term = forms.ChoiceField(choices = PERIOD_CHOICES, widget=forms.Select(attrs={'id':"term", 'name': "minbeds"}))

views.py

class CreditsList(ListView):
    model = Credit
    template_name = 'credits/credit_listing.html'

    def get(self, request, *args, **kwargs):
        self.object_list = self.get_queryset()
        little_form = CreditFilterForm(self.request.GET or None, prefix="little")
        ...

class LittleForm(FormView):
    form_class = CreditFilterForm

模板

<form action="{% url 'little_form' %}" method="post">
    {% csrf_token %}
    {{ little_form.as_p }}
    <input type="submit" name="{{ little_form.prefix }}" value="Submit">
</form>

1 个答案:

答案 0 :(得分:2)

prefix适用于所有表单输入小部件。但是在您的LittleForm视图中,您没有使用该前缀。

您可以通过覆盖prefix attribute [Django-doc]来添加它:

class LittleForm(FormView):
    form_class = CreditFilterForm
    prefix = 'little'
  

注意:我建议将LittleForm重命名为LittleFormView。这样可以更清楚地知道该类是什么,并且如果以后构造具有相同名称的表单,它将避免“冲突”。