You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I performed a lot experiments with the optgroups method but have no success, by some reason first form submission get failed validation and validates successfully on the next submit.
A very dirty hack to make it works (nothing related to select2 module, just maybe it will helps to faster understand core of the issue.
class ModelChoiceField2(ChoiceField):
def to_python(self, value):
if value in self.empty_values:
return None
try:
key = self.to_field_name or 'pk'
if isinstance(value, self.queryset.model):
value = getattr(value, key)
value = self.queryset.get(**{'pk': value}) <<<<< HERE changed key to 'pk'
value = value
except (ValueError, TypeError, self.queryset.model.DoesNotExist):
raise ValidationError(self.error_messages['invalid_choice'], code='invalid_choice')
return value
def valid_value(self, value):
# Override validation to check is selected value exists in the db
text_value = str(value)
if not self.queryset.model(slug=text_value):
return False
return True
class ModelBForm(ModelForm):
a_slug = ModelChoiceField2()
...
I recently fixed the same issue in Django's autocomplete field. I'd be delighted if you could try to backport this patch to this repo as well. I am pretty overwhelmed with work right now, so I'd appreciate the help.
Hi @codingjoe, I faced an issue using
to_field
option in the model field. Form can't be validated at all.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 theoptgroups
method value is alwayspk
ModelSelect2Mixin
in theoptgroups
lineto
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 theto_python
methodbecause it gets pk value instead slug.
The text was updated successfully, but these errors were encountered: