0

ModelForms are a nice way to prevent repeating the definitions of models one creates. What I would like to do is take advantage of that feature and use it for more than just processing POST requests. I use forms a lot for validation.

Example:

Say you have a User model with the fields (email, password, first_name, last_name). The email field is unique and an index.

UserCreationForm: uses all fields, fails validation if the email already exists. Processes POST requests UserUpdateForm: the same model, but doesn't allow to change the email. Because this field is excluded no issues there. UserAuthenticationForm: includes only the email and password fields. The problem is, this should be used for authentication and validation fails because the email already exists.

Is there a way I can do this? That is, have the UserAuthenticationForm skip the email checking.

Thank you.

André Fratelli
  • 5,920
  • 7
  • 46
  • 87
  • It would be a very odd tweak that might affect your code later, coding the form for authentication isn't that hard. You will be better following programming principle *separation of concerns* http://en.wikipedia.org/wiki/Separation_of_concerns and letting each part of your software focus on its own objective. – Paulo Bu May 15 '13 at 14:48
  • Hmm.. I don't think the logic separation is the issue. The form is doing something very spefic. – André Fratelli May 15 '13 at 14:54
  • What I meant in the comment was the same you did in your answer. You have a form for creating/updating objects, don't use it for log users. Use it just for what it was created. – Paulo Bu May 15 '13 at 15:00
  • I get it now! ;) I'm already making the changes. Thank you. – André Fratelli May 15 '13 at 15:04

1 Answers1

0

ModelForms are for creating/updating objects. Authentication doesn't modify the model instance (the User), therefore use a normal form instead.

From the docs:

The save() method

Every form produced by ModelForm also has a save() method. This method creates and saves a database object from the data bound to the form. A subclass of ModelForm can accept an existing model instance as the keyword argument instance; if this is supplied, save() will update that instance. If it’s not supplied, save() will create a new instance of the specified model.

If you weren't going to use this save(), method and you don't need most of the model fields either (only username/email and password), you would be throwing away most of the functionality offered by the ModelForm, so why would you use it in the first place?

Adrián
  • 6,135
  • 1
  • 27
  • 49