Search code examples
djangodjango-modelsdjango-admindjango-authentication

DJANGO - Admin Action


I'd like to create a website with for car dealer with admin and allow dealers to add, edit, delete car.

My problem is that on Django Admin, when I login with any account I see all the cars and I'd like to show only cars attched to connected dealer.

I create a model

from django.db import models
from django.contrib.auth.models import User
import datetime
from brand.models import Brands
from django.urls import reverse

class Car(models.Model):
 dealer = models.ForeignKey(User, on_delete=models.DO_NOTHING)
 brand = models.ForeignKey(Brands, on_delete=models.DO_NOTHING)
 carname = models.CharField(max_length=100)
 def __str__(self):
 return '%s %s' % (self.brand, self.carname)

Also, when I create a car the dealer's list show all dealers in database, but me I'd like to display only connected account name.

Thanks for your help


Solution

  • In Django Admin class you can define has_view_permission method https://docs.djangoproject.com/en/3.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.has_view_permission

    for example:

    class CarAdmin(admin.ModelAdmin):
        def has_view_permission(request, obj=None):
            if request.user == obj.dealer:
                return True
            else:
                return False