Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin custom validation - require at least one inline foreign-key model

I have two Django models (Purchaser and LineItem) that I manage via the stock admin interface. The dumbed-down versions:

class Purchaser(models.Model):
    firstname = models.CharField('First Name', max_length = 30)
    lastname = models.CharField('Last Name', max_length = 30)
    paymentid = models.IntegerField('Payment ID', unique = True)

class LineItem(models.Model):
    purchaser = models.ForeignKey(Purchaser)
    ship_first_name = models.CharField('Recipient First Name', max_length = 50)
    ship_last_name = models.CharField('Recipient Last Name', max_length = 50)

I have LineItems as an inline within the Purchaser admin page, and want to require that Purchasers have at least one LineItem (i.e. not let the user save a new Purchaser unless they have added at least one LineItem). Is there a clean way to do this? I already have some validation set up using a custom modelForm, but that method only deals with Purchaser fields, and not anything to do with LineItems. Advice?

like image 330
Nick Avatar asked May 01 '11 20:05

Nick


1 Answers

You can use the answer information referenced here: Django: Forcing admin users to enter at least one item in TabularInline

Hope that helps you out.

like image 198
Brandon Avatar answered Oct 07 '22 08:10

Brandon