Bula
Bula

Reputation: 2792

Forms fields respecting DRY django

Given some forms in Django (take the following for simplicity)

class LoginRegisterForm(forms.Form):

  email = forms.EmailField(label="Email", max_length=100)
  password = forms.CharField(label="Password", widget=forms.PasswordInput(), max_length=100)

We're trying to restrict the submission of these forms if there are additional fields submitted so we have the following added method to our form class

    def correct_fields(self):
      return set(self.data.keys()) == {"Email", "Password"}

And the following code in the views.py method corresponding to the submission of this form:

if form.is_valid() and form.correct_fields:

How can we avoid having to write Email and Password in both the definition of the form and the correct_fields method? Does django offer a build-in function to prevent forms being submitted if the correct fields are not submitted? (The form is still submitted if the correct fields and some additional fields are given). If this functionality is not given, how do I avoid writing the fields twice?

Upvotes: 2

Views: 46

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477160

Fields where you do not specify required=False are required. As the documentation on the required=… parameter [Django-doc] says:

By default, each Field class assumes the value is required, so if you pass an empty value – either None or the empty string ("") – then clean() will raise a ValidationError exception.

So it will already validate that data indeed contains email and password. You can define optional fields with:

class LoginRegisterForm(forms.Form):
    email = forms.EmailField(label="Email", max_length=100)
    password = forms.CharField(label="Password", widget=forms.PasswordInput(), max_length=100)
    info = forms.CharField(label="Tell us someting", required=False, intial='')

Upvotes: 1

Related Questions