Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin - Is it possible to limit a user's access to only his own inputted data?

In other words, I would like to disallow users from editing or viewing anything but their own inputted data, throughout all applications.

I read here that this may be impossible with the built in admin application. If so is there an extension available?

Thanks

like image 597
Nathan Katz Avatar asked Aug 16 '11 00:08

Nathan Katz


People also ask

How do I restrict access to parts of Django admin?

Django admin allows access to users marked as is_staff=True . To disable a user from being able to access the admin, you should set is_staff=False . This holds true even if the user is a superuser. is_superuser=True .

How can we set restrictions on views in Django?

Restrict access to unauthenticated users in Django Views. To simply restrict access to a view based on if the user is authenticated (logged in) or not does not require you to dive deep into the permission system at all, you can simply do it with Decorators, Mixins or the user is_authenticated property.

Is Django admin good for production?

Django's Admin is amazing. A built-in and fully functional interface that quickly gets in and allows data entry is priceless. Developers can focus on building additional functionality instead of creating dummy interfaces to interact with the database.


1 Answers

It can be done. You need to create the appropriate modelAdmin in your admin.py first.

For list "display" filtering modify the queryset method:

class MyModelAdmin(admin.ModelAdmin):

    def queryset(self, request):
        return Entry.objects.filter(owner=request.user)

For field filtering, depending on the field type you want to limit you override the appropriate method.

Related django documentation is here: https://docs.djangoproject.com/en/1.3/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_foreignkey

To limit foreignkey field output you can do something like this: (from the django documentation)

class MyModelAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "car": # The name of the field you want to limit
            kwargs["queryset"] = Car.objects.filter(owner=request.user)
        return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
like image 67
monkut Avatar answered Oct 30 '22 16:10

monkut