Select2 widget showing on Django Admin site but not on the form template in Django4

392 Views Asked by At

I have two object models, NewsObject and StockObject. The stock object is a foreign key in the news object.

class stockObject(models.Model):
    stock_name = CharField(max_length=100, blank=True, null=True)
    stock_tag = CharField(max_length=100, blank=True, null=True)

    def __str__(self):
        return self.stock_name

class newsObject(models.Model):
    title = CharField(max_length=100, blank=True, null=True)
    body = TextField(blank=True, null=True)
    stock = ForeignKey(stockObject, on_delete=models.SET_NULL, blank=True, null=True)

I have used autocomplete_fields property in the ModelAdmin class as I want a searchable dropdown for stocks in news. I have also added search_fields in the stocks ModelAdmin as mentioned in the documentation.

This is what my admin.py looks like:

class stockAdmin(admin.ModelAdmin):
    list_display = ['stock_name', 'stock_tag']
    search_fields = ['stock_name']

class newsAdmin(admin.ModelAdmin):
    list_display = ['title', 'body', 'stock']
    search_fields = ['title', 'body', 'stock']
    autocomplete_fields = ['stock']

Now, the issue is that I get a searchable dropdown on the Django Admin site for this field, but it is only a dropdown (not searchable) on the actual template screen. I have a basic view which calls the template, like so:

Views.py

def createNews(request):
    form = NewsForm()
    if request.method == 'POST':
        form = NewsForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/backoffice/')

    context = {'form' : form}
    return render(request, 'NewsForm.html', context)

And NewsForm.html is:

{% extends "base.html" %}

{% load static %}
       {% block content %} 
       <form action="" method="POST">
           {% csrf_token %}
           {{ form }}
           <input type="submit" name="Submit">
       </form>
{% endblock %} 

I've been wondering what might be the cause of this behavior. Tried multiple things but none of them work. What might I be missing here?

Django Admin site imageDjango Admin site image

Django Template ImageDjango Template Image

1

There are 1 best solutions below

3
On

I think you have written all your models in camelCase so first changed them to PascalCase.

Second, you have missed models in all your models:

Write them like this add models before every datatype like:

from django.db import models

class Musician(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    instrument = models.CharField(max_length=100)

Not only datatype of fields.