I’m implementing a Django Form witch should contain the field ‘fieldA’ from modelA
:
class ModelA(models.Model): fieldA = models.CharField(max_length=8) ...
My question is: Is there a way to have Django form, which will automatically handle validation of fieldA (check the max_length)? I know I Could use form.ModelForm
class referring to ModelA, but then the form would reflect all the fields of the ModelA. I would like to use simple forms.Form
.
I’m looking for a solution like:
class formX(forms.Form): fieldA = forms.CharField(**modelA.fieldA.constraints) fieldB = ... some other fields not related to ModelA ... .... even more fields
Advertisement
Answer
I found a way how to achieve a validation of form Field reflecting constrains from model Field.
class Foo(models.Model): x = models.CharField(max_length=30) y = models.IntegerField(null=True) class FooForm(forms.Form): foo_x = forms.CharField(validators=Foo._meta.get_field('x').validators)
Like this, the form will respect the max_length
validator of attribute x
or any other validator defined.