Django Form - This field is required.What am I missing.

282 views
Skip to first unread message

Johan

unread,
Jan 22, 2012, 5:42:53 AM1/22/12
to Django users
Hi I have a form that has a required email field. This due to the fact
that the model requires an email. However, I don't display the email
field on the form. So when the post gets back into my view the email
field is empty. I then thought I would do the following just before
the form.is_valid() :

form = students.forms.StudentForm(request.POST)
form.instance.email=user.email

User is a session variable which contains the correct email for the
session. The above code however still fail with is_valid. I even
changed the forms clean_email() to return the correct email. But, I
still get 'This field is required'.

Any help would be appreciated.

James

unread,
Jan 22, 2012, 9:04:32 AM1/22/12
to Django users
One:

You can change the default behavior of the widget so it is hidden. The
email address will come back in the post data (this means you don't
mind the email address in the raw html). This also assumes you are
using modelforms.

Two:

Alter the POST data upon return so you add the email address to it.

Three:

Create the model first (or retrieve the existing model) and do this
instead: form = students.forms.StudentForm(request.POST,
instance=students_model)

Four:

Again, assuming you are using model forms, change the email address
field to (blank=True, null=True). Once you save the modelform and a
model is returned, you can then save the email address directly to the
field, eg:

model = form.save(commit=False)
model.email = email
model.save()

(it might be you don't have to have null=True if you always do commit
= False, I'm not 100% certain)

I think any of those should work as a workaround for your problem.

Daniel Roseman

unread,
Jan 22, 2012, 11:28:57 AM1/22/12
to django...@googlegroups.com
If you don't want the email field to be displayed or validated, you should exclude it from the form by using the `exclude` tuple in the form's Meta class.  Then, on saving, you can do:
    student = form.save(commit=False)
    student.email = user.email
    student.save()
--
DR.
Reply all
Reply to author
Forward
0 new messages