Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter django admin by logged in user

I'm new to django. I'm creating simple app in which I have users enter some data and view it later. I need to make django admin show to the user only the data she enter and non of the other users data. Is it possible to change it to multiple admin pages?

Thank you

like image 449
Ido Ran Avatar asked Mar 05 '12 22:03

Ido Ran


2 Answers

  • Store a reference to a user in your model.

models.py:

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

class MyModel(models.Model):
    user = models.ForeignKey(User)
    ... (your fields) ...
  • Force the current user to be stored in that field (when using admin)
  • Force any list of these objects to be (additionally) filtered by the current user (when using admin)
  • Prevent other users from editing (even though they can't see the object in the list they could access its change_form directly)

admin.py:

from django.contrib import admin
from models import MyModel

class FilterUserAdmin(admin.ModelAdmin): 
    def save_model(self, request, obj, form, change):
        obj.user = request.user
        obj.save()

    def get_queryset(self, request): 
        # For Django < 1.6, override queryset instead of get_queryset
        qs = super(FilterUserAdmin, self).get_queryset(request) 
        return qs.filter(created_by=request.user)

    def has_change_permission(self, request, obj=None):
        if not obj:
            # the changelist itself
            return True
        return obj.user === request.user

class MyModelAdmin(FilterUserAdmin):
    pass   # (replace this with anything else you need)
admin.site.register(MyModel, MyModelAdmin)

If you have MyOtherModel with a foreign key "user" just subclass MyOtherModelAdmin from FilterUserAdmin in the same manner.

If you want certain superusers to be able to see anything, adjust queryset() and has_change_permission() accordingly with your own requirements (e.g. don't filter/forbid editing if request.user.username=='me'). In that case you should also adjust save_model() so that your editing doesn't set the user and thus "take away" the object from the previous user (e.g. only set user if self.user is None (a new instance)).

like image 194
Danny W. Adair Avatar answered Oct 21 '22 04:10

Danny W. Adair


You'll have to save in the user to every item and query each item with that user as search criteria. You'll probably build a base model which all your other models will inherit from. To get you started take a look at row-level permissions in the admin.

like image 30
darren Avatar answered Oct 21 '22 05:10

darren