Home > Enterprise >  How I can show the table of all user which role is based on specific values
How I can show the table of all user which role is based on specific values

Time:01-03

I have a User Table in Django. It has different role values. I would like to show all user which role is based on a specific value.

I would like to show all user in Django admin panel which role is couple only.

In admin.py:

from django.contrib import admin
from django.contrib.auth import admin as auth_admin
from django.contrib.auth import get_user_model

from users.forms import UserChangeForm, UserCreationForm
from users.models import EmailConfirmationToken

User = get_user_model()


@admin.register(User)
class UserAdmin(auth_admin.UserAdmin):

    form = UserChangeForm
    add_form = UserCreationForm
    fieldsets = (("User", {"fields": ("name", "wedding_date", "wedding_zip_code", "role", "photo", "subscription", "leads")}),)   auth_admin.UserAdmin.fieldsets
    list_display = ["username", "name", "is_superuser", "is_active"]
    search_fields = ["name", "subscription"]

enter image description here

CodePudding user response:

I did manage to solve this problem, by defining a variable in my model.py file

called

#models.py 

role_couple = models.CharField(max_length=7, default='couple')
role_vendor = models.CharField(max_length=7, default='vendor')

and then i changed the admin.py file to this

#admin.py 


list_display = ('role_couple' , 'N1' , 'N2' , 'N3')


another solution is to add default_filters variable:

for example

#admin.py 


list_filters = ('role',)
default_filters = { 'role':'couple'} 

am sorry if the first one didn't helped you

BG

CodePudding user response:

I got the solution by customizing the queryset in ModelAdmin Class.

@admin.register(User)
  class UserAdmin(auth_admin.UserAdmin):

    form = UserChangeForm
    add_form = UserCreationForm
    fieldsets = (("User", {"fields": ("name", "wedding_date", "wedding_zip_code", "role", "photo", "subscription", "leads")}),)   auth_admin.UserAdmin.fieldsets
    list_display = ["username", "name", "is_superuser", "is_active"]
    search_fields = ["name", "subscription"]
    
    def get_queryset(self, request):
        qs = super(UserAdmin, self).get_queryset(request)
        if  request.user.is_superuser:
            return qs.filter(role='couple')
        return qs
  • Related