Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin dropdown of 1000s of users

Hypothetically: I have a model called Car, which relates to one user. My concern is within the default Django Admin. I assign a user to a car via a drop down (this is default Django behavior, so I'm told).

What happens when I have 1000s+ of users to pick from in the drop down. Does the admin deal with this, if so how?

like image 641
Prometheus Avatar asked Feb 16 '13 17:02

Prometheus


3 Answers

You can look into django-grappelli, which is an app that enhances the admin interface. The documentation describes an autocomplete for ForeignKey or ManyToMany relationships, using raw_id_fields.

like image 20
msc Avatar answered Oct 16 '22 19:10

msc


The default admin UI displays a dropdown list. Use the raw_id_fields option to get a pop-up window, via a search button. This window lets you find and select the linked object. See the documentation: https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#django.contrib.admin.ModelAdmin.raw_id_fields

By default, Django’s admin uses a select-box interface () for fields that are ForeignKey. Sometimes you don’t want to incur the overhead of having to select all the related instances to display in the drop-down.

like image 137
Mark Lavin Avatar answered Oct 16 '22 21:10

Mark Lavin


You can use django-select2 plugin https://github.com/applegrew/django-select2.

You can do something like:

from django_select2 import AutoModelSelect2Field

class CategoryChoices(AutoModelSelect2Field):
    queryset = models.Category.objects
    search_fields = ['name__icontains', 'code__icontains']

class NewsAdminForm(forms.ModelForm):
    category = CategoryChoices()

    class Meta:
        model = models.News
        exclude = ()

# register in admin
class NewsAdmin(admin.ModelAdmin):
    form = NewsAdminForm
admin.site.register(News, NewsAdmin)
like image 5
Ranju R Avatar answered Oct 16 '22 21:10

Ranju R