0

I'm using django_select2 "ModelSelect2Widget" and get on html-form "No results found". What is wrong?

models.py

class Department(Catalog):
    name = models.CharField(max_length=50, unique=True)

class Person(Catalog):
    surname = models.CharField(max_length=50)
    name = models.CharField(max_length=50)
    department = models.ForeignKey(Department, on_delete=models.PROTECT)

forms.py

class MyWidget(ModelSelect2Widget):
    model = Department
    search_fields = ['name__icontains', ]


class PersonForm(ModelForm):
    class Meta:
        model = Person
        fields = ['surname', 'name', 'department']
        widgets = {'department': MyWidget}
Nikita Konyshev
  • 93
  • 1
  • 1
  • 6

2 Answers2

0

Below change in your form code will work in form PersonForm and remov fields completely:

widgets={
            'surname':forms.TextInput(attrs={'class':'form-control'}), 
            'name':forms.TextInput(attrs={'class':'form-control'}),
            'department':MyWidget(attrs={'class':'form-control'}),
        }

The complete PersonForm form should be like :

class PersonForm(ModelForm):
    class Meta:
       model = Person
       exclude = () # If you have any column like datetime add that into `exclude`
       widgets={
        'surname':forms.TextInput(attrs={'class':'form-control'}),
        'name':forms.TextInput(attrs={'class':'form-control'}),
        'department':MyWidget(attrs={'class':'form-control'}),
       }
Anup Yadav
  • 2,825
  • 3
  • 21
  • 30
  • I change and it doesn't help – Nikita Konyshev Nov 30 '18 at 07:44
  • Without fields attribute get error "Creating a ModelForm without either the fields attribute or the exclude attribute is prohibited". With fields attr still "no results" – Nikita Konyshev Nov 30 '18 at 08:00
  • Then add `exclude` Please check my latest edit. If you have any column like datetime add that into `exclude` OR rest columns which aren't in exclude add those into this. Hopefully this you'll find working – Anup Yadav Nov 30 '18 at 08:45
  • Add exclude. The same situation. – Nikita Konyshev Nov 30 '18 at 08:53
  • I think that everything is done like in documentation select2_django. No error messages. In web server log there are messages like "GET /catlg/person/245/?term=test&field_id=NjE2ND...... HTTP/1.1 200 4969" – Nikita Konyshev Nov 30 '18 at 09:04
0

It's my mistake. I have installed "SELECT2" exсept "django-select2". I disabled "SELECT2" by removing its links, but leave "django-select2" links. And now MyWidget works fine.

Nikita Konyshev
  • 93
  • 1
  • 1
  • 6