1
0
mirror of https://github.com/django/django.git synced 2025-10-24 14:16:09 +00:00

Fixed #8209: ModelForms now validate unique constraints. Alex Gaynor did much of this work, and Brian Rosner helped as well.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@8805 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Jacob Kaplan-Moss
2008-09-01 19:08:08 +00:00
parent 5f31e9bd33
commit ea05e61b2b
5 changed files with 229 additions and 11 deletions

View File

@@ -73,6 +73,22 @@ class Restaurant(Place):
def __unicode__(self):
return self.name
class Product(models.Model):
slug = models.SlugField(unique=True)
def __unicode__(self):
return self.slug
class Price(models.Model):
price = models.DecimalField(max_digits=10, decimal_places=2)
quantity = models.PositiveIntegerField()
def __unicode__(self):
return u"%s for %s" % (self.quantity, self.price)
class Meta:
unique_together = (('price', 'quantity'),)
class MexicanRestaurant(Restaurant):
serves_tacos = models.BooleanField()
@@ -553,4 +569,56 @@ True
>>> type(_get_foreign_key(MexicanRestaurant, Owner))
<class 'django.db.models.fields.related.ForeignKey'>
# unique/unique_together validation ###########################################
>>> FormSet = modelformset_factory(Product, extra=1)
>>> data = {
... 'form-TOTAL_FORMS': '1',
... 'form-INITIAL_FORMS': '0',
... 'form-0-slug': 'car-red',
... }
>>> formset = FormSet(data)
>>> formset.is_valid()
True
>>> formset.save()
[<Product: car-red>]
>>> data = {
... 'form-TOTAL_FORMS': '1',
... 'form-INITIAL_FORMS': '0',
... 'form-0-slug': 'car-red',
... }
>>> formset = FormSet(data)
>>> formset.is_valid()
False
>>> formset.errors
[{'slug': [u'Product with this Slug already exists.']}]
# unique_together
>>> FormSet = modelformset_factory(Price, extra=1)
>>> data = {
... 'form-TOTAL_FORMS': '1',
... 'form-INITIAL_FORMS': '0',
... 'form-0-price': u'12.00',
... 'form-0-quantity': '1',
... }
>>> formset = FormSet(data)
>>> formset.is_valid()
True
>>> formset.save()
[<Price: 1 for 12.00>]
>>> data = {
... 'form-TOTAL_FORMS': '1',
... 'form-INITIAL_FORMS': '0',
... 'form-0-price': u'12.00',
... 'form-0-quantity': '1',
... }
>>> formset = FormSet(data)
>>> formset.is_valid()
False
>>> formset.errors
[{'__all__': [u'Price with this Price and Quantity already exists.']}]
"""}