﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
34635	ModelChoiceField with a to_attr that can have an EMPTY_VALUE	Willem Van Onsem	nobody	"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."	Uncategorized	closed	Forms	4.2	Normal	wontfix			Unreviewed	0	0	0	0	0	0
