Skip to content

Django Select2 ModelSelect2TagWidget Problem #131

Closed

Description

@auditsbydanny

I followed the documentation on how to use the ModelSelect2TagWidget, but when I submit the form I get "Select a valid choice error" on the tag field regardless the tag is saved in the database.

models.py

class FromTo(models.Model):
    from_to = models.CharField(max_length=100)

class Course(models.Model):
    from_to = models.ForeignKey(
            FromTo, null=True, on_delete=models.SET_NULL)

forms.py

class FromToWidget(s2forms.ModelSelect2TagWidget):
    queryset = models.FromTo.objects.all()
    search_fields = ['from_to__icontains']

    def value_from_datadict(self, data, files, name):
        values = super().value_from_datadict(data, files, name)

        queryset = self.get_queryset()
        pks = queryset.filter(
            **{'pk__in': [v for v in values if v.isdigit()]}).values_list('pk', flat=True)
        cleaned_values = []
        for val in values:
            if represent_int(val) and int(val) not in pks or not represent_int(val) and force_text(val) not in pks:
                val = queryset.create(from_to=val).pk
            cleaned_values.append(val)
        return cleaned_values

class CourseModelForm(forms.ModelForm):
    from_to = forms.ModelChoiceField(
        models.FromTo.objects.all(), widget=FromToWidget(model=models.FromTo))

Activity

  1. Repository owner locked and limited conversation to collaborators on Apr 9, 2022
  2. converted this issue into a discussion #134 on Apr 9, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions