Django form returns is_valid() = False and no erro

2020-08-13 05:45发布

I have simple view in django app, which I want to show only when one of the forms is valid. I have something like:

@login_required
@require_role('admin')
def new_package(request):
    invoicing_data_form = InvoicingDataForm(instance=request.user.account.company.invoicingdata)
    if invoicing_data_form.is_valid():
        # all here
        return HttpResponse('Form valid')
    else:
        logger.info("Form invalid")
        return HttpResponse(json.dumps(invoicing_data_form.errors)

I always get log info message that form is invalid, however, I get nothing in

invoicing_data_form.errors

It is very strange, because I am validating this form in other view using user input data and it works just fine. Any idea?

EDIT: Just for clarification. I am not requesting any data from user in this form. I am using this form to validate some model instance (this form is subclassing from ModelForm).

4条回答
▲ chillily
2楼-- · 2020-08-13 06:14

That's because you're not "feeding" your form.

Do this:

invoicing_data_form = InvoicingDataForm(instance=invoice, data=request.POST or None)
查看更多
甜甜的少女心
3楼-- · 2020-08-13 06:18

I got this for AuthenticationForm which needs AuthenticationForm(None, request.POST) see Using AuthenticationForm in Django

查看更多
走好不送
4楼-- · 2020-08-13 06:19

You have an unbound form. https://docs.djangoproject.com/en/1.7/ref/forms/api/#bound-and-unbound-forms

A Form instance is either bound to a set of data, or unbound.

If it’s bound to a set of data, it’s capable of validating that data and rendering the form as HTML with the data displayed in the HTML.

If it’s unbound, it cannot do validation (because there’s no data to validate!), but it can still render the blank form as HTML.

To bind data to a form, pass the data as a dictionary as the first parameter to your Form class constructor:

invoicing_data_form = InvoicingDataForm(request.POST or None, instance=invoice)
查看更多
神经病院院长
5楼-- · 2020-08-13 06:19

If you're already giving request.POST to your form using request.POST or None, but it's still invalid without errors, check that there isn't any redirect going on. A redirect loses your POST data and your form will be invalid with no errors because it's unbound.

查看更多
登录 后发表回答