Hi @codingjoe, I faced an issue using to_field option in the model field. Form can't be validated at all.
class ModelA(models.Model):
id = models.AutoField(primary_key=True)
slug = models.CharField(max_length=4, unique=True)
class ModelB(models.Model):
id = models.AutoField(primary_key=True)
a_slug = models.ForeignKey(ModelA, verbose_name=_("Select A"), on_delete=models.CASCADE, to_field='slug')
note = models.CharField(_("Note"), max_length=50)
class ModelAPickWidget(s2forms.ModelSelect2Widget):
model = ModelA
search_fields = [
"slug__icontains",
]
def label_from_instance(self, obj):
return str(f'{obj.slug}')
class ModelBForm(ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# self.fields['a_slug'].widget = ModelAPickWidget()
# self.fields['a_slug'].widget.attrs['class'] = 'form-control'
# self.fields['a_slug'].to_field_name = 'slug'
# self.fields['a_slug'].queryset = ModelA.objects.all()
class Meta:
model = ModelB
fields = ['a_slug', 'note', ]
widgets = {
"a_slug": ModelAPickWidget(attrs={
'class': 'form-control',
}),
"note": widgets.TextInput(attrs={
'class': 'form-control',
}),
}
If I going to disable ModelAPickWidget to use default Django's select widget it works and saves the form.
There is some debugging information.
ModelSelect2Mixin in the optgroups method value is always pk
ModelSelect2Mixin in the optgroups line
query = Q(**{"%s__in" % field_name: selected_choices})
print(query)
>>> (AND: ('slug__in', {'196'}))
- I tried to change
query = Q(**{"%s__in" % field_name: selected_choices})
to
query = Q(**{"%s__in" % 'pk': selected_choices})
And I got some success, form get failed validation on first submission but saves if I re-submit it again.
Form validation error raised by Django's ModelChoiceField in the to_python method
Select a valid choice. That choice is not one of the available choices.
because it gets pk value instead slug.
Hi @codingjoe, I faced an issue using
to_fieldoption in the model field. Form can't be validated at all.If I going to disable
ModelAPickWidgetto use default Django's select widget it works and saves the form.There is some debugging information.
ModelSelect2Mixinin theoptgroupsmethod value is alwayspkModelSelect2Mixinin theoptgroupslineto
And I got some success, form get failed validation on first submission but saves if I re-submit it again.
Form validation error raised by Django's
ModelChoiceFieldin theto_pythonmethodbecause it gets pk value instead slug.