6

I have a form field with autocomplete (using django-autocomplete-light app and Select2 widget), which serve as a search filter and it works as expected.

When I submit the form and search results are listed, I would like to set this form field initial value to previously submitted value - so the user can adjust some of the search parameters instead of setting up all search filters from scratch.

This form field will be used to choose one of the ~10000 values, so I need it to load values on-demand. As the form field is not prepopulated with any values, I have no idea how it would be possible to set initial value.

models.py

class Location(models.Model):
    place = models.CharField(max_length=50)
    postal_code = models.CharField(max_length=5)

views.py

class LocationAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):
        qs = Location.objects.all()
        if self.q:
            qs = qs.filter(place__istartswith=self.q) | qs.filter(postal_code__istartswith=self.q)
        return qs

forms.py

class LocationForm(forms.ModelForm):        
    class Meta:
        model = Location
        fields = ('place',)
        widgets = {
            'place': autocomplete.Select2(url='location_autocomplete')
        }

Any suggestions?

Thanks!

1 Answers1

0

In your views.py if you pass place value like this:

LocationForm(initial={'place': place })

It will be pre-populated in your form.

Docs: https://docs.djangoproject.com/en/1.11/ref/forms/fields/#initial

Paolo
  • 20,112
  • 21
  • 72
  • 113
rsb
  • 412
  • 4
  • 14