#34635: ModelChoiceField with a to_attr that can have an EMPTY_VALUE
--------------------------------------------+------------------------
               Reporter:  Willem Van Onsem  |          Owner:  nobody
                   Type:  Uncategorized     |         Status:  new
              Component:  Uncategorized     |        Version:  4.2
               Severity:  Normal            |       Keywords:
           Triage Stage:  Unreviewed        |      Has patch:  0
    Needs documentation:  0                 |    Needs tests:  0
Patch needs improvement:  0                 |  Easy pickings:  0
                  UI/UX:  0                 |
--------------------------------------------+------------------------
 Recently a person asked this question on
 [StackOverflow](https://stackoverflow.com/questions/76409430/django-
 testing-a-simple-model-with-foreign-key-and-updateview/76409867). Imagine
 we have the following models:

 {{{
 from django.db import models

 class Location(models.Model):
     location_number = models.CharField(max_length=30, unique=True)
     name = models.CharField(max_length=128)

 class Project(models.Model):
     location = models.ForeignKey(Location, on_delete=models.CASCADE,
 to_field='location_number', db_column='location_number',
 related_name='projects', verbose_name='Standort')
 }}}

 Then it is possible to construct a `Location` with an empty string for
 `location_number`:

 {{{
 Location.objects.create(location_number='', name='location_name')
 }}}

 But now if we construct a `ModelForm`, it will not accept this as valid
 option, indeed:

 {{{
 class ProjectForm(forms.ModelForm):
     class Meta:
         model = Project
         fields = ['location']
 }}}

 This will render a `<select>` with the values of the `to_field` as values,
 so:

 {{{
 <select name="location">
   <option value="">location_name</option>
 </select>
 }}}

 now if the form is submitted, it will pass the empty string for
 `location`, but the form field will reject it because the field is
 required, and it sees this as an empty value.

 The problem is thus a bit of a mismatch between what a form does and the
 possible values of a model. Unfortunately I don't see an easy solution for
 this. Perhaps the checks framework can at least warn if a `ForeignKey`
 refers to a `CharField` or another field that can have an empty value.

-- 
Ticket URL: <https://code.djangoproject.com/ticket/34635>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/010701888fd2d534-c2c47b35-607c-4685-832e-31759ab4569e-000000%40eu-central-1.amazonses.com.

Reply via email to