django form errors before submit

2.7k views Asked by At

My django form has errors in the initial page load, before the form even has a chance to be submitted.

My view:

def example_function(request):
    if request.method == 'POST':
        # the request is GET
    else:
        form = MyForm(user=request.user)
        import pdb;pdb.set_trace()

return render_to_response('templates/example.html', locals(), context_instance=RequestContext(request),)

Where I have my pdb imported, in the console I can see that my form already has errors. The output of form.errors in my console is all the fields in the model which are set to not null.

(Pdb) form.errors
{'example_field_1': [u'This field is required.'], 'example_field_2': [u'This field is required.']}

The form has not submit yet, but I am still getting errors. Can someone explain?

I'm using django 1.4.

My form:

class MyForm(forms.ModelForm):
    captcha = ReCaptchaField()
    _readonly_template = form.TextInput(attrs={'readonly':'readonly'})
    first_name = forms.CharField(widget = _readonly_tempalte)

    def __init__(self, data=None, *args, **kwargs):
        data = data or {}
        if 'user' in kwargs:
            user = kwargs['user']
            del kwargs['user']
            data.update({
                'first_name' : user.first_name,
            })

        super(MyForm, self).__init__(data, *args, **kwargs)

    class Meta:
        model = MyModel

My model:

class MyModel(models.Model):
    first_name = models.CharField(max_length=255)
    example_field_1 = models.CharField(max_length=255)
    example_field_2 = models.CharField(max_length=255)
5

There are 5 answers

2
Paul Collingwood On

Don't you need to do something like this

form = NameForm(request.POST)

Rather then attempting to use the user object to populate the form? Will the user object have an example_field_1 in it?

https://docs.djangoproject.com/en/1.8/topics/forms/

0
Pavan Patel On

https://docs.djangoproject.com/en/1.8/ref/forms/validation/

accessing the form.errors attribute will trigger the various form validation methods. Those errors shouldn't show up when you render the form.

0
Sylvain Biehler On

This is the normal behavior.

Some properties of fields are checked on client side. The error messages belong to the form, are part of the html but are not displayed until needed. It saves a client-server request.

0
Adrian Stanica On

Not sure if still useful, but adding it here, as I just ran into this for my ChoiceField items within my form.

I was getting the same error messages, but eventually found out I had forgotten to ad 'or None' when initiating the form inside my view.

The initial code inside my view function that was displaying the error messages from the start:

form=FormName(request.POST)

I just added the 'or None' to it:

form=FormName(request.POST or None)

And all good after that.

0
catonalake On

I'm not sure how the user field is structured, but keep in mind that if you want the user name, you may want to change that from request.user to request.user.username.

I hope you resolved your issue, but in case you haven't, I had a similar issue which I was able to resolve by using "or None" when setting the form after checking if it is a POST (or GET) request.

In your case it looks like this may be a slightly different issue, but I wondered if this snippet might fix things up:

if request.method == "POST":
    form = MyForm(request.POST or None)
    # .. do stuff....
else:      #.....this is a GET
    data = {'user': request.user.username}   #note this is changed to username
    form = MyForm(data)