Skip to content

Instantly share code, notes, and snippets.

@antonagestam
Last active August 29, 2015 14:11
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 antonagestam/c69278ddc6deac5f2294 to your computer and use it in GitHub Desktop.
Save antonagestam/c69278ddc6deac5f2294 to your computer and use it in GitHub Desktop.
Configurable Model Form
from django import forms
class ConfigurableModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ConfigurableModelForm, self).__init__(*args, **kwargs)
opts = self.Meta
if hasattr(opts, 'field_conf'):
self.update_fields(opts.field_conf)
def set_field_attr(self, field, attr, val):
setattr(self.fields[field], attr, val)
def update_field(self, field, conf):
for attr, val in conf.iteritems():
self.set_field_attr(field, attr, val)
def update_fields(self, field_conf):
for field, conf in field_conf.iteritems():
self.update_field(field, conf)
from .forms import ConfigurableModelForm
class MyForm(ConfigurableModelForm):
class Meta:
model = MyModel
fields = ['email']
field_conf = {
'email': {
'error_messages': {'unique': 'My awesome error message for violating unique values'},
'required': False,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment