Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Ensure that custom primary keys are always shown on a formset. Refs #…

…7938. Thanks magneto for discovering this problem.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@8179 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit af35fb1fbb48e6125b313ad35238cd06fa3ce7b5 1 parent 61b3357
Brian Rosner authored August 01, 2008
5  django/forms/models.py
@@ -378,8 +378,9 @@ def save_new_objects(self, commit=True):
378 378
 
379 379
     def add_fields(self, form, index):
380 380
         """Add a hidden field for the object's primary key."""
381  
-        self._pk_field_name = self.model._meta.pk.attname
382  
-        form.fields[self._pk_field_name] = IntegerField(required=False, widget=HiddenInput)
  381
+        if self.model._meta.has_auto_field:
  382
+            self._pk_field_name = self.model._meta.pk.attname
  383
+            form.fields[self._pk_field_name] = IntegerField(required=False, widget=HiddenInput)
383 384
         super(BaseModelFormSet, self).add_fields(form, index)
384 385
 
385 386
 def modelformset_factory(model, form=ModelForm, formfield_callback=lambda f: f.formfield(),
14  tests/modeltests/model_formsets/models.py
@@ -29,6 +29,10 @@ class AuthorMeeting(models.Model):
29 29
     def __unicode__(self):
30 30
         return self.name
31 31
 
  32
+class CustomPrimaryKey(models.Model):
  33
+    my_pk = models.CharField(max_length=10, primary_key=True)
  34
+    some_field = models.CharField(max_length=100)
  35
+
32 36
 
33 37
 __test__ = {'API_TESTS': """
34 38
 
@@ -330,5 +334,15 @@ def __unicode__(self):
330 334
 <p><label for="id_test-0-title">Title:</label> <input id="id_test-0-title" type="text" name="test-0-title" maxlength="100" /><input type="hidden" name="test-0-id" id="id_test-0-id" /></p>
331 335
 <p><label for="id_test-1-title">Title:</label> <input id="id_test-1-title" type="text" name="test-1-title" maxlength="100" /><input type="hidden" name="test-1-id" id="id_test-1-id" /></p>
332 336
 
  337
+# Test a custom primary key ###################################################
  338
+
  339
+We need to ensure that it is displayed
  340
+
  341
+>>> CustomPrimaryKeyFormSet = modelformset_factory(CustomPrimaryKey)
  342
+>>> formset = CustomPrimaryKeyFormSet()
  343
+>>> for form in formset.forms:
  344
+...     print form.as_p()
  345
+<p><label for="id_form-0-my_pk">My pk:</label> <input id="id_form-0-my_pk" type="text" name="form-0-my_pk" maxlength="10" /></p>
  346
+<p><label for="id_form-0-some_field">Some field:</label> <input id="id_form-0-some_field" type="text" name="form-0-some_field" maxlength="100" /></p>
333 347
 
334 348
 """}

0 notes on commit af35fb1

Please sign in to comment.
Something went wrong with that request. Please try again.