Skip to content

Instantly share code, notes, and snippets.

@marcoala
Last active January 4, 2017 17:22
Show Gist options
  • Select an option

  • Save marcoala/7e67841460a5847224d08d5c008009d6 to your computer and use it in GitHub Desktop.

Select an option

Save marcoala/7e67841460a5847224d08d5c008009d6 to your computer and use it in GitHub Desktop.
A small class for django form that allow to create Form field from Model when you are not using a ModelForm
class FieldBuilder(object):
"""Return the default form field for a model field. This field will be validated oin the same
way as the form field would be on a ModelForm.
Optionally, extra kwargs can be added to override what the form field is initialized with.
So this:
class ExampleForm(forms.ModelForm):
class Meta:
model = ExampleModel
fields = ['example_field']
is equivalent to:
class ExampleForm(forms.Form):
example_field = FieldBuilder(ExampleModel, 'example_field')
Usage:
class ExampleCreationForm(forms.Form):
example_field = FieldBuilder(ExampleModel, 'example_field')
# The original field in the model has blank=True, we can override it here
different_field = FieldBuilder(AnotherExampleModel, 'different_field', required=True)
def save(self):
data = self.cleaned_data
obj = ExampleModel(example_field=data['example_field'])
obj2 = AnotherExampleModel(different_field=data['different_field'])
obj.save()
obj2.save()
"""
def __new__(cls, model, field_name, **kwargs):
model_field = model._meta.get_field(field_name)
return model_field.formfield(**kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment