Code

Ticket #8209: django-8209.diff

File django-8209.diff, 11.6 KB (added by Alex, 6 years ago)

Tiny change from brosner's patch

Line 
1diff --git a/django/forms/models.py b/django/forms/models.py
2index 4563ace..6ceabbc 100644
3--- a/django/forms/models.py
4+++ b/django/forms/models.py
5@@ -3,9 +3,10 @@ Helper functions for creating Form classes from Django models
6 and database field objects.
7 """
8 
9-from django.utils.translation import ugettext_lazy as _
10 from django.utils.encoding import smart_unicode
11 from django.utils.datastructures import SortedDict
12+from django.utils.text import get_text_list
13+from django.utils.translation import ugettext_lazy as _
14 
15 from util import ValidationError, ErrorList
16 from forms import BaseForm, get_declared_fields
17@@ -20,6 +21,11 @@ __all__ = (
18     'ModelMultipleChoiceField',
19 )
20 
21+try:
22+    any
23+except NameError:
24+    from django.utils.itercompat import any # pre-2.5
25+
26 def save_instance(form, instance, fields=None, fail_message='saved',
27                   commit=True, exclude=None):
28     """
29@@ -202,6 +208,47 @@ class BaseModelForm(BaseForm):
30             object_data.update(initial)
31         super(BaseModelForm, self).__init__(data, files, auto_id, prefix, object_data,
32                                             error_class, label_suffix, empty_permitted)
33+    def clean(self):
34+        self.validate_unique()
35+        return self.cleaned_data
36+   
37+    def validate_unique(self):
38+        from django.db.models.fields import FieldDoesNotExist
39+        unique_checks = list(self.instance._meta.unique_together[:])
40+        form_errors = []
41+        for name, field in self.fields.items():
42+            try:
43+                f = self.instance._meta.get_field_by_name(name)[0]
44+            except FieldDoesNotExist:
45+                # This is an extra field that's not on the model, ignore it
46+                continue
47+            if name in self.cleaned_data and f.unique:
48+                unique_checks.append((name,))
49+        for unique_check in [check for check in unique_checks if not any([x in self._errors for x in check])]:
50+            kwargs = dict([(field_name, self.cleaned_data[field_name]) for field_name in unique_check])
51+            qs = self.instance.__class__._default_manager.filter(**kwargs)
52+            if self.instance.pk is not None:
53+                qs = qs.exclude(pk=self.instance.pk)
54+            if qs.extra(select={'a': 1}).values('a').order_by():
55+                model_name = self.instance._meta.verbose_name.title()
56+                if len(unique_check) == 1:
57+                    field_name = unique_check[0]
58+                    field_label = self.fields[field_name].label
59+                    self._errors[field_name] = ErrorList([
60+                        _("%(model_name)s with this %(field_label)s already exists.") % \
61+                        {'model_name': model_name, 'field_label': field_label}
62+                    ])
63+                else:
64+                    field_labels = [self.fields[field_name].label for field_name in unique_check]
65+                    field_labels = get_text_list(field_labels, _('and'))
66+                    form_errors.append(
67+                        _("%(model_name)s with this %(field_label)s already exists.") % \
68+                        {'model_name': model_name, 'field_label': field_labels}
69+                    )
70+                for field_name in unique_check:
71+                    del self.cleaned_data[field_name]
72+        if form_errors:
73+            raise ValidationError(form_errors)
74 
75     def save(self, commit=True):
76         """
77@@ -246,19 +293,27 @@ class BaseModelFormSet(BaseFormSet):
78                  queryset=None, **kwargs):
79         self.queryset = queryset
80         defaults = {'data': data, 'files': files, 'auto_id': auto_id, 'prefix': prefix}
81-        if self.max_num > 0:
82-            qs = self.get_queryset()[:self.max_num]
83-        else:
84-            qs = self.get_queryset()
85-        defaults['initial'] = [model_to_dict(obj) for obj in qs]
86+        defaults['initial'] = [model_to_dict(obj) for obj in self.get_queryset()]
87         defaults.update(kwargs)
88         super(BaseModelFormSet, self).__init__(**defaults)
89-
90+   
91+    def _construct_form(self, i, **kwargs):
92+        if i < self._initial_form_count:
93+            kwargs['instance'] = self.get_queryset()[i]
94+        return super(BaseModelFormSet, self)._construct_form(i, **kwargs)
95+       
96     def get_queryset(self):
97-        if self.queryset is not None:
98-            return self.queryset
99-        return self.model._default_manager.get_query_set()
100-
101+        if not hasattr(self, '_queryset'):
102+            if self.queryset is not None:
103+                qs = self.queryset
104+            else:
105+                qs = self.model._default_manager.get_query_set()
106+            if self.max_num > 0:
107+                self._queryset = qs[:self.max_num]
108+            else:
109+                self._queryset = qs
110+        return self._queryset
111+   
112     def save_new(self, form, commit=True):
113         """Saves and returns a new model instance for the given form."""
114         return save_instance(form, self.model(), exclude=[self._pk_field.name], commit=commit)
115@@ -358,6 +413,17 @@ class BaseInlineFormSet(BaseModelFormSet):
116             self._total_form_count = self._initial_form_count
117             self._initial_form_count = 0
118         super(BaseInlineFormSet, self)._construct_forms()
119+   
120+    def _construct_form(self, i, **kwargs):
121+        form = super(BaseInlineFormSet, self)._construct_form(i, **kwargs)
122+        if self.save_as_new:
123+            try:
124+                # Remove the primary key from the form's data, we are only
125+                # creating new instances
126+                del form.data[form.add_prefix(self._pk_field.name)]
127+            except KeyError:
128+                pass
129+        return form
130 
131     def get_queryset(self):
132         """
133diff --git a/django/utils/itercompat.py b/django/utils/itercompat.py
134index c166da3..1b24cc9 100644
135--- a/django/utils/itercompat.py
136+++ b/django/utils/itercompat.py
137@@ -72,3 +72,10 @@ def sorted(in_value):
138     out_value = in_value[:]
139     out_value.sort()
140     return out_value
141+
142+def any(seq):
143+    """any implementation."""
144+    for x in seq:
145+        if seq:
146+            return True
147+    return False
148diff --git a/docs/topics/forms/modelforms.txt b/docs/topics/forms/modelforms.txt
149index d161b3f..163c428 100644
150--- a/docs/topics/forms/modelforms.txt
151+++ b/docs/topics/forms/modelforms.txt
152@@ -338,6 +338,16 @@ parameter when declaring the form field::
153    ...     class Meta:
154    ...         model = Article
155 
156+Overriding the clean() method
157+-----------------------------
158+
159+You can overide the ``clean()`` method on a model form to provide additional
160+validation in the same way you can on a normal form.  However, by default the
161+``clean()`` method validates the uniqueness of fields that are marked as unique
162+on the model, and those marked as unque_together, if you would like to overide
163+the ``clean()`` method and maintain the default validation you must call the
164+parent class's ``clean()`` method.
165+
166 Form inheritance
167 ----------------
168 
169@@ -500,4 +510,4 @@ books of a specific author. Here is how you could accomplish this::
170     >>> from django.forms.models import inlineformset_factory
171     >>> BookFormSet = inlineformset_factory(Author, Book)
172     >>> author = Author.objects.get(name=u'Orson Scott Card')
173-    >>> formset = BookFormSet(instance=author)
174\ No newline at end of file
175+    >>> formset = BookFormSet(instance=author)
176diff --git a/tests/modeltests/model_forms/models.py b/tests/modeltests/model_forms/models.py
177index 5f714fb..9a306aa 100644
178--- a/tests/modeltests/model_forms/models.py
179+++ b/tests/modeltests/model_forms/models.py
180@@ -117,9 +117,26 @@ class CommaSeparatedInteger(models.Model):
181     def __unicode__(self):
182         return self.field
183 
184+class Product(models.Model):
185+    slug = models.SlugField(unique=True)
186+   
187+    def __unicode__(self):
188+        return self.slug
189+
190+class Price(models.Model):
191+    price = models.DecimalField(max_digits=10, decimal_places=2)
192+    quantity = models.PositiveIntegerField()
193+   
194+    def __unicode__(self):
195+        return u"%s for %s" % (self.quantity, self.price)
196+   
197+    class Meta:
198+        unique_together = (('price', 'quantity'),)
199+
200 class ArticleStatus(models.Model):
201     status = models.CharField(max_length=2, choices=ARTICLE_STATUS_CHAR, blank=True, null=True)
202 
203+
204 __test__ = {'API_TESTS': """
205 >>> from django import forms
206 >>> from django.forms.models import ModelForm, model_to_dict
207@@ -1132,8 +1149,42 @@ u'1,,2'
208 >>> f.clean('1')
209 u'1'
210 
211-# Choices on CharField and IntegerField
212+# unique/unique_together validation
213 
214+>>> class ProductForm(ModelForm):
215+...     class Meta:
216+...         model = Product
217+>>> form = ProductForm({'slug': 'teddy-bear-blue'})
218+>>> form.is_valid()
219+True
220+>>> obj = form.save()
221+>>> obj
222+<Product: teddy-bear-blue>
223+>>> form = ProductForm({'slug': 'teddy-bear-blue'})
224+>>> form.is_valid()
225+False
226+>>> form._errors
227+{'slug': [u'Product with this Slug already exists.']}
228+>>> form = ProductForm({'slug': 'teddy-bear-blue'}, instance=obj)
229+>>> form.is_valid()
230+True
231+
232+# ModelForm test of unique_together constraint
233+>>> class PriceForm(ModelForm):
234+...     class Meta:
235+...         model = Price
236+>>> form = PriceForm({'price': '6.00', 'quantity': '1'})
237+>>> form.is_valid()
238+True
239+>>> form.save()
240+<Price: 1 for 6.00>
241+>>> form = PriceForm({'price': '6.00', 'quantity': '1'})
242+>>> form.is_valid()
243+False
244+>>> form._errors
245+{'__all__': [u'Price with this Price and Quantity already exists.']}
246+
247+# Choices on CharField and IntegerField
248 >>> class ArticleForm(ModelForm):
249 ...     class Meta:
250 ...         model = Article
251diff --git a/tests/modeltests/model_formsets/models.py b/tests/modeltests/model_formsets/models.py
252index 332c5a7..1e25baa 100644
253--- a/tests/modeltests/model_formsets/models.py
254+++ b/tests/modeltests/model_formsets/models.py
255@@ -73,6 +73,22 @@ class Restaurant(Place):
256     def __unicode__(self):
257         return self.name
258 
259+class Product(models.Model):
260+    slug = models.SlugField(unique=True)
261+
262+    def __unicode__(self):
263+        return self.slug
264+
265+class Price(models.Model):
266+    price = models.DecimalField(max_digits=10, decimal_places=2)
267+    quantity = models.PositiveIntegerField()
268+
269+    def __unicode__(self):
270+        return u"%s for %s" % (self.quantity, self.price)
271+
272+    class Meta:
273+        unique_together = (('price', 'quantity'),)
274+
275 class MexicanRestaurant(Restaurant):
276     serves_tacos = models.BooleanField()
277 
278@@ -553,4 +569,56 @@ True
279 >>> type(_get_foreign_key(MexicanRestaurant, Owner))
280 <class 'django.db.models.fields.related.ForeignKey'>
281 
282+# unique/unique_together validation ###########################################
283+
284+>>> FormSet = modelformset_factory(Product, extra=1)
285+>>> data = {
286+...     'form-TOTAL_FORMS': '1',
287+...     'form-INITIAL_FORMS': '0',
288+...     'form-0-slug': 'car-red',
289+... }
290+>>> formset = FormSet(data)
291+>>> formset.is_valid()
292+True
293+>>> formset.save()
294+[<Product: car-red>]
295+
296+>>> data = {
297+...     'form-TOTAL_FORMS': '1',
298+...     'form-INITIAL_FORMS': '0',
299+...     'form-0-slug': 'car-red',
300+... }
301+>>> formset = FormSet(data)
302+>>> formset.is_valid()
303+False
304+>>> formset.errors
305+[{'slug': [u'Product with this Slug already exists.']}]
306+
307+# unique_together
308+
309+>>> FormSet = modelformset_factory(Price, extra=1)
310+>>> data = {
311+...     'form-TOTAL_FORMS': '1',
312+...     'form-INITIAL_FORMS': '0',
313+...     'form-0-price': u'12.00',
314+...     'form-0-quantity': '1',
315+... }
316+>>> formset = FormSet(data)
317+>>> formset.is_valid()
318+True
319+>>> formset.save()
320+[<Price: 1 for 12.00>]
321+
322+>>> data = {
323+...     'form-TOTAL_FORMS': '1',
324+...     'form-INITIAL_FORMS': '0',
325+...     'form-0-price': u'12.00',
326+...     'form-0-quantity': '1',
327+... }
328+>>> formset = FormSet(data)
329+>>> formset.is_valid()
330+False
331+>>> formset.errors
332+[{'__all__': [u'Price with this Price and Quantity already exists.']}]
333+
334 """}