Question

I have a field in one of the models like :

field = models.CharField(max_length=10, null=True)

in admin.py I have

readonly_fields = ('field',)

When I try to save it from the admin, it does not throw a validation error which is quite sane.

But if I try to do this in my views.py ,

form = MyForm(#some data here from request.POST)
print form.is_valid()

I get error saying :

'this field is required'

Here MyForm is a ModelForm for that model. I am trying to create another form to replace the admin form so that my team can use the new form that I have created instead of the admin.

I want to run that form through ModelForm that I have already written and I don't want to repeat code and re-write validation.

Why is this behavior different between admin form and any other form ? Is saying blank=True in my models the only way to make this work ?

Was it helpful?

Solution

There are two ways in which you can solve this. In your ModelForm:

  1. either exclude that field.
  2. or set it to required=False.

Way #1:

class MyForm(forms.ModelForm):
    model = MyModel
    exclude = ['field']

Way #2:

class MyForm(forms.ModelForm):
    model = MyModel

    field = forms.Charfield(required=False)

Which way is better?

If you do not want that field to be editable, you should go with way #1. But if you want this field to be editable but not required, go with way #2.

OTHER TIPS

You might want to read this source.

From the accepted answer

null=True sets NULL (versus NOT NULL) on the column in your DB. Blank values for Django field types such as DateTimeField or ForeignKey will be stored as NULL in the DB.

blank=True determines whether the field will be required in forms. This includes the admin and your own custom forms. If blank=True then the field will not be required, whereas if it's False the field cannot be blank.

In addition

From source

readonly_fields will be excluded in ModelForm used for creating and editing in the admin.

Update

As for solving your problem, you can exclude it in your modelform or set the field to required=False. More on that here source.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top