Django Autocomplete Light Foreign Key не рендерится

Кажется, я перепробовал все, но все равно мое поле не отображается. Моя цель состоит в том, чтобы иметь возможность найти продукты, написав их названия. Я пытался следовать этому руководству: https://django-autocomplete-light.readthedocs.io/en/master/tutorial.html#tutorial

Мои различные файлы выглядят следующим образом:

models.py:

# Product class
class Product(models.Model):
    name = models.CharField(max_length=100)
    sku = models.CharField(max_length=50, unique=True)
    category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT, default=get_default_category)
    availability = models.CharField(max_length=20, choices=[('E', 'Existent'), ('O', 'On demand')])
    price = models.IntegerField(default=0)

    def __str__(self):
        return self.name

# Sales orders class
class SaleID(models.Model):
    date = models.DateTimeField()

class Sale(models.Model):
    ID = models.ForeignKey(SaleID, on_delete=models.CASCADE)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    quantity = models.PositiveIntegerField()
    total_price = models.PositiveIntegerField()

    def __str__(self):
        return f"Sale of {self.quantity} {self.product.name} for {self.total_price}"

forms.py:

from dal import autocomplete

# Add Product Form to add products
class SaleForm(forms.ModelForm):
    product = forms.ModelChoiceField(queryset=Product.objects.all(), widget=autocomplete.ModelSelect2(url='product-autocomplete'))
    quantity = forms.IntegerField(required=True, widget=forms.NumberInput(attrs={"placeholder":"Enter quantity", "class":"form-control"}), label="")

    class Meta:
        model = Sale
        fields = ("product", "quantity")  # Define the fields to include from the Product model
        exclude = ("user", "ID", "total_price")

SaleModelFormSet = modelformset_factory(Sale, form=SaleForm, extra=1, can_delete=False)

views.py:

# SALES ADD    
def add_sale(request):
    if request.user.is_authenticated:
        if request.method == "POST":
            saleid_instance = SaleID.objects.create(date=timezone.now())
            sale_formset = SaleModelFormSet(request.POST)  # Create instance of SaleFormSet
            if sale_formset.is_valid():
                saleid_instance.date=timezone.now()

                for sale_form in sale_formset:
                    if sale_form.cleaned_data.get('product') and sale_form.cleaned_data.get('quantity'):    # Check it has product and quantity
                        # Assign the ID to the sale before saving
                        sale_form_instance = sale_form.save(commit=False)
                        sale_form_instance.ID = saleid_instance # Assigning saleID to the form
                        sale_form_instance.total_price = sale_form_instance.product.price * sale_form_instance.quantity
                        sale_form.save()

                messages.success(request, "Sales added successfully")
                return redirect('home')
        else:
            sale_formset = SaleModelFormSet(queryset=SaleID.objects.none())  # Create instance of VariantFormSet
        return render(request, 'website/add_sale.html', {'sale_formset': sale_formset})  # Pass variant_formset to template
    else:
        messages.warning(request, "You must be logged in to do that")
        return redirect('home')
    
#Product autocomplete with dal:
class ProductAutocomplete(autocomplete.Select2QuerySetView):
    # Don't forget to filter out results depending on the visitor !
    def get_queryset(self):
        print("hello")
        if not self.request.user.is_authenticated:
            return Product.objects.none()
       
        qs = Product.objects.all().order_by('name') 
        if self.q:
            qs = qs.filter(name__icontains=self.q)
        return qs

Мой urls.py:

urlpatterns = [
    ...
    path('add_sale/', views.add_sale, name='add_sale'),     
    path('product-autocomplete/', ProductAutocomplete.as_view(), name='product-autocomplete'),
    ...
]

Когда я перехожу по URL/product-autocomplete, он выдает мне список продуктов

{"results": [{"id": "3", "text": "Conejo", "selected_text": "Conejo"}, {"id": "1", "text": "Casa", "selected_text": "Casa"}, {"id": "2", "text": "Madera", "selected_text": "Madera"}], "pagination": {"more": false}}

Моя база.html

<!-- Loads Bootstrap Framework -->
<!doctype html>
<html lang="en">
{% load static %}

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Inventory Management System</title>

  <!-- Include DAL JS -->
  <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

  <!-- Include Font Awesome CSS -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">
  <!-- Include Bootstrap 5 CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
  <link rel="shortcut icon" href="{% static 'website/favicon.ico' %}">
  
</head>

Я считаю, что проблема в моем файле add_sale.html. Я использовал этот учебник: https://medium.com/all-about-django/adding-forms-dynamically-to-a-django-formset-375f1090c2b0, чтобы иметь несколько форм (моя идея состоит в том, чтобы добавить несколько товаров в одну продажу).

Итак, мой add_sale.html выглядит следующим образом:

В настоящее время страница add_sale выглядит следующим образом:

enter image description here

Я не знаю, где ошибка, и как ее исправить :(.

Любая помощь будет очень признательна.

Я пробовал загружать различные js файлы, изменял add_sale.html, но все равно мои товары не отображаются в поле товара.

Вернуться на верх