Tony Suffolk 66
Tony Suffolk 66

Reputation: 9724

Django - conditional mandatory fields

I have a Django form to capture Username/Password and a Sign-In button. Clearly I need Username/Password to be mandatory.

I also want to have a Register button on the same form, where the Username/Password fields can't be mandatory.

How do I validate the form in a way that is dependent on the button that has been pressed.

Normally Validation is done on the forms clean method, but the clean method has no access to the selected button - just the entered fields.

Upvotes: 0

Views: 846

Answers (1)

Tony Suffolk 66
Tony Suffolk 66

Reputation: 9724

I have discovered the answer - it is not very well documented in the official documents - so here it is :

Within the clean method on the form as well as having access to the cleaned data, the program also has access to self.data which is the uncleaned data - i.e with the hidden fields, and buttons available (the cleaned data only has the input fields available but not the input type="submit" buttons- so my html form has this (approximately) :

<form method="post" action="" >                    
    <table>                
        <tr>
           <th><label for="id_username">Username:</label></th>
            <input type="text" name="username" id="id_username" maxlength="30" /></td></tr>
        <tr>
           <th><label for="id_password">Password:</label></th><input type="password" name="password" id="id_password" /></td></tr>
        <tr>
            <td><input type='submit' name='register' value='Register'/></td>
            <td><input type='submit' name='submit' value='Sign In'/></td>
        </tr>
    </table>
</form>

and in my Django form - the clean method is :

def clean(self):
    cleaned_data = super().clean()
    register = self.data.get('register')
    signin = self.data.get('submit')

    if signin:
        if not (cleaned_data.get('username') and cleaned_data.get('password')):
             self.add_error('username', 'Must provide your scouts.org.uk Username to sign in')
             self.add_error('password', 'Must provide your scouts.org.uk password to sign in')

        return cleaned_data
    elif register:
        return cleaned_data

Note the use of self.data to access the form data for the buttons

Upvotes: 1

Related Questions