Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline Form Validation in Django

I would like to make an entire inline formset within an admin change form compulsory. So in my current scenario when I hit save on an Invoice form (in Admin) the inline Order form is blank. I'd like to stop people creating invoices with no orders associated.

Anyone know an easy way to do that?

Normal validation like (required=True) on the model field doesn't appear to work in this instance.

like image 901
user108791 Avatar asked May 18 '09 13:05

user108791


People also ask

How do I check if a form is valid in Django?

The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.

What is inline formset in Django?

Django formset allows you to edit a collection of the same forms on the same page. It basically allows you to bulk edit a collection of objects at the same time.

What is clean method in Django?

The clean() method on a Field subclass is responsible for running to_python() , validate() , and run_validators() in the correct order and propagating their errors. If, at any time, any of the methods raise ValidationError , the validation stops and that error is raised.

How do I display validation error in Django?

To display the form errors, you use form. is_valid() to make sure that it passes validation. Django says the following for custom validations: Note that any errors raised by your Form.


1 Answers

The best way to do this is to define a custom formset, with a clean method that validates that at least one invoice order exists.

class InvoiceOrderInlineFormset(forms.models.BaseInlineFormSet):     def clean(self):         # get forms that actually have valid data         count = 0         for form in self.forms:             try:                 if form.cleaned_data:                     count += 1             except AttributeError:                 # annoyingly, if a subform is invalid Django explicity raises                 # an AttributeError for cleaned_data                 pass         if count < 1:             raise forms.ValidationError('You must have at least one order')  class InvoiceOrderInline(admin.StackedInline):     formset = InvoiceOrderInlineFormset   class InvoiceAdmin(admin.ModelAdmin):     inlines = [InvoiceOrderInline] 
like image 59
Daniel Roseman Avatar answered Oct 24 '22 14:10

Daniel Roseman