Skip to content

Instantly share code, notes, and snippets.

@loicteixeira
Created April 17, 2017 06:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loicteixeira/ccc405a1c94aef573e4bdb9fdb38337d to your computer and use it in GitHub Desktop.
Save loicteixeira/ccc405a1c94aef573e4bdb9fdb38337d to your computer and use it in GitHub Desktop.
[Django] Dynamically require a field
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')
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