Skip to content

Does not work with to_field #100

Open
@rez0n

Description

@rez0n

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.

  1. ModelSelect2Mixin in the optgroups method value is always pk
  2. ModelSelect2Mixin in the optgroups line
query = Q(**{"%s__in" % field_name: selected_choices})
print(query)
>>> (AND: ('slug__in', {'196'}))
  1. 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.

Metadata

Metadata

Labels

bugSomething isn't working

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions