M
M
Mikhail2019-02-14 12:38:04
Django
Mikhail, 2019-02-14 12:38:04

How to add a list of users id to Django-Admin field?

In the system table User, you need to store a list of users. Let's say the field will be CharField, How to make the Django admin panel enter usernames (in the form of tags with usernames), but save, preferably as an id?
It’s easier on the frontend, but here you need to shovel a bunch of docks if you haven’t come across this ...
Even if I figured out how to expand / replace the User table itself.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2019-02-14
@lightarhont

https://github.com/applegrew/django-select2
https://github.com/asyncee/django-easy-select2

A
Andrey Bogoyavlensky, 2019-02-14
@abogoyavlensky

If I understood the question correctly, I can offer such a solution.
Add to the overridden user model, for example, MyUser field m2m to the same model:

from django.contrib.auth.models import AbstractUser
from django.db import models

class MyUser(AbstractUser):
    ...
    users = models.ManyToManyField('self', blank=True)

Django>=2.0 added the ability to autocomplete ForeignKey and ManyToMany fields in the admin out of the box. To do this, you need to add `autocomplete_fields` to the admin panel of the model, where you need a "field with tags" and "search_fields" - on the model by which we will search for a related entity. In this case, it's the same model:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as AuthUserAdmin
from django.utils.translation import ugettext_lazy as _

@admin.register(User)
class MyUserAdmin(AuthUserAdmin):
    ...
    fieldsets = AuthUserAdmin.fieldsets + ((_('Users'), {
        'fields': ('users', )
    }), )
    search_fields = ['first_name', 'last_name']
    autocomplete_fields = ['users']

UPD: If Django version is <2.0, then a separate package can be used in the admin panel https://django-autocomplete-light.readthedocs.io/e...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question