Created
April 17, 2017 06:50
-
-
Save loicteixeira/ccc405a1c94aef573e4bdb9fdb38337d to your computer and use it in GitHub Desktop.
[Django] Dynamically require a field
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django import forms | |
class MyForm(forms.Form): | |
def clean(self): | |
is_something = cleaned_data.get('is_something') | |
if is_something: | |
validate_required_field(self, cleaned_data, 'name_of_dynamically_required_field') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.core.validators import EMPTY_VALUES | |
def validate_required_field(form, cleaned_data, field_name, message="This field is required."): | |
""" | |
Mark a field as required if not present or empty | |
:type form: django.forms.Form | |
:param form: The form | |
:type cleaned_data: dict | |
:param cleaned_data: The form cleaned data | |
:type field_name: str | |
:param field_name: The required field name | |
:type message: str | |
:param message: The error message. Default to `The field is required`. | |
:rtype: None | |
:return: Nothing | |
""" | |
missing_field = field_name not in cleaned_data | |
empty_field = not missing_field and cleaned_data[field_name] in EMPTY_VALUES | |
if missing_field or empty_field: | |
form.add_error(field_name, message) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment