django-autocomplete-light: Forward works fine in admin but returns None when used in template

1.8k views Asked by At

I can't get django-autocomplete-light to forward values when NOT in admin. Here's the issue: I have 2 linked select boxes. It is for a train connections app, so when you select City from the first box (departure) only the destination-Cities for which there is a connection should appear on the second.

The simplified models:

class City(models.Model):
    name = models.CharField(max_length=64)
    destinations = models.ManyToManyField(
        'self',
        symmetrical=False,
        through='Connection')

class Connection(models.Model):
    departure = models.ForeignKey(
        City,
        on_delete=models.CASCADE,
        related_name='departure')
    destination = models.ForeignKey(
        City,
        on_delete=models.CASCADE,
        related_name='destination')

And here are my views:

class DepartureAutocomplete(autocomplete.Select2QuerySetView):

    def get_queryset(self):
        qs = City.objects.all()
        if self.q:
            qs = qs.filter(name__istartswith=self.q)
        return qs


class DestinationAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):
        qs = City.objects.all()
        departure = self.forwarded.get('departure', None)
        if not departure:
            return []
        else:
            qs = qs.filter(id=departure)[0].destinations.all()
        if self.q:
            qs = qs.filter(name__istartswith=self.q)
        return qs


class HomeView(generic.UpdateView):
    model = City
    form_class = ConnectionForm
    template_name = 'intercity/home_template.html'
    success_url = reverse_lazy('home_view')

    def get_object(self):
        return City.objects.first()

Finally my forms.py:

class ConnectionForm(forms.ModelForm):
    departure = forms.ModelChoiceField(
        queryset=City.objects.all(),
        widget=autocomplete.ModelSelect2(
            url='departure-autocomplete'
        )
    )
    destination = forms.ModelChoiceField(
        queryset=City.objects.all(),
        widget=autocomplete.ModelSelect2(
            url='destination-autocomplete',
            forward=['departure', ]
        )
    )

    class Meta:
        model = Connection
        fields = ('__all__')

Everything works fine in admin (in the Add Connection page), but I need to expose this to the front end. The rendered html structure seems the same as in the admin page, but the forwarded id of the first select field is not passed correctly (None).

Any tips/help appreciated!

1

There are 1 answers

0
fekioh On

OK - got it. In case I can save anyone else from wasting time as I did:

In the template, I was just rendering {{ form.as_p }} It should be inside a form tag! As in:

<form>
    {{ form.as_p }}
</form>