0

I am building a web app in Django trying to use django-autocomplete-light(v.3.8.2) to create an auto-complete field. I have form that allows users to create a Trade record. I'm trying to add an auto-complete field for Trade.owned_game (a lookup field). I am just getting an empty dropdown field for the auto-complete field (screenshot attached at bottom of this post) Below is my code:

models.py:

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse

class Game(models.Model):
    name = models.TextField()  # Unrestricted text
    platform = models.CharField(max_length=100)  # character field
    created_date = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.name  # return game name when game.objects.all() is called


class Trade(models.Model):
    name = models.TextField() # Unrestricted text
    created_date = models.DateTimeField(default=timezone.now)
    is_trade_proposed = models.BooleanField(default=False)
    user_who_posted = models.ForeignKey(User, on_delete=models.CASCADE)
    owned_game = models.ForeignKey(Game, on_delete=models.CASCADE, related_name='owned_game', db_column='owned_game')

    def __str__(self):
        return self.name # return game name when game.objects.all() is called

urls.py:

from django.urls import path
from django.conf.urls import url
from .views import (
    PostListView,
    TradeListView,
    PostDetailView,
    TradeCreateView,
    GameAutoComplete,
    PostUpdateView,
    PostDeleteView,
    UserPostListView
)
from . import views

urlpatterns = [
    path('', views.home, name='blog-home'),
    path('post/new/', views.trade_new, name='trade-create'),
    url(
        r'^game-autocomplete/$',
        GameAutoComplete.as_view(),
        name='game-autocomplete')
    ,
]

views.py:

from django.shortcuts import render, get_object_or_404
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.models import User
from django.views.generic import (
    ListView,
    DetailView,
    CreateView,
    UpdateView,
    DeleteView
)
from .models import Trade, Game

def trade_new(request):
    form = TradeCreateForm()
    return render(request, 'blog/trade_form.html', {'form': form, 'title': 'asdf'})


class TradeCreateForm(forms.ModelForm):
    game = forms.ModelChoiceField(
        queryset=Game.objects.all(),
        to_field_name = 'name',
        widget=autocomplete.ModelSelect2(url='game-autocomplete')
    )

    class Meta:
        model = Trade
        fields = ['owned_game', 'desired_game']


class TradeCreateView(LoginRequiredMixin, CreateView):
    model = Trade
    fields = ["owned_game"]


class GameAutoComplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):
        if not self.request.user.is_authenticated:
            return Game.objects.none()

        qs = Game.objects.all()

        if self.q:
            qs = qs.filter(name__istartswith=self.q)

        return qs

trade_form.html:

{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
    <div class="content-section">
        <form method="POST">
            {% csrf_token %}
            <fieldset class="form-group">
                <legend class="border-bottom mb-4">Propose New Trade</legend>
                {{ form|crispy }}



                {{ form.media }}
            </fieldset>
            <div class="form-group">
                <button class="btn btn-outline-info" type="submit">Submit</button>
            </div>
        </form>
    </div>
{% endblock content %}

Screenshot:

enter image description here

I have tried the solutions from these similar StackOverflow questions but they're not working:

Tom
  • 364
  • 2
  • 19

1 Answers1

0

I should have checked the javascript console earlier! The problem was one of the <link ...> scripts for jQuery was invalid. Once i fixed that, the auto-complete field worked

Tom
  • 364
  • 2
  • 19