Ticket #10792: 10792_r10524.diff

File 10792_r10524.diff, 2.7 KB (added by Carl Meyer, 15 years ago)

patch with test and doc update

  • django/forms/models.py

     
    711711                 required=True, widget=None, label=None, initial=None,
    712712                 help_text=None, to_field_name=None, *args, **kwargs):
    713713        self.empty_label = empty_label
     714        if required and (initial is not None):
     715            self.empty_label = None
    714716        self.cache_choices = cache_choices
    715717
    716718        # Call Field instead of ChoiceField __init__() because we don't need
  • tests/regressiontests/forms/models.py

     
    2424    """For ModelChoiceField and ModelMultipleChoiceField tests."""
    2525    name = models.CharField(max_length=10)
    2626
     27class ChoiceOptionModel(models.Model):
     28    """Destination for ChoiceFieldModel's ForeignKey.
     29    Can't reuse ChoiceModel because error_message tests require that it have no instances."""
     30    name = models.CharField(max_length=10)
     31   
     32class ChoiceFieldModel(models.Model):
     33    """Model with ForeignKey to another model, for testing ModelForm
     34    generation with ModelChoiceField."""
     35    choice = models.ForeignKey(ChoiceOptionModel, blank=False,
     36                               default=lambda: ChoiceOptionModel.objects.all()[0])
     37
    2738class FileModel(models.Model):
    2839    file = models.FileField(storage=temp_storage, upload_to='tests')
    2940
     
    8697>>> instance_form.initial['value']
    879812
    8899>>> shutil.rmtree(temp_storage_location)
     100
     101In a ModelForm with a ModelChoiceField, if the model's ForeignKey has blank=False and a default,
     102no empty option is created (regression test for #10792).
     103
     104First we need at least one instance of ChoiceOptionModel:
     105
     106>>> ChoiceOptionModel.objects.create(name='default')
     107<ChoiceOptionModel: ChoiceOptionModel object>
     108
     109>>> class ChoiceFieldForm(ModelForm):
     110...     class Meta:
     111...         model = ChoiceFieldModel
     112>>> list(ChoiceFieldForm().fields['choice'].choices)
     113[(1, u'ChoiceOptionModel object')]
     114
    89115"""}
  • docs/ref/forms/fields.txt

     
    786786        # No empty label
    787787        field2 = forms.ModelChoiceField(queryset=..., empty_label=None)
    788788
     789   Note that if a ``ModelChoiceField`` is required and has a default
     790   initial value, no empty choice is created (regardless of the value
     791   of ``empty_label``).
     792
    789793``ModelMultipleChoiceField``
    790794~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    791795
Back to Top