Last active
August 29, 2015 14:11
-
-
Save antonagestam/c69278ddc6deac5f2294 to your computer and use it in GitHub Desktop.
Configurable Model Form
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 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) |
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 .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