filtertips
filtertips

Reputation: 903

Django admin site - limit user content on user

admin.py:

from django.contrib import admin
from .models import Blog


admin.site.register(Blog)

I have figured out that Django admin serves my needs very well. The only thing I would like to limit is that Users could write/read/edit the Blog applications but for their own entries only.

If Alice posts a blog, she can read/write/edit only her posts and not the posts of Bob. Does Django allow anything like this in the admin site or do I need to develop my code?

Upvotes: 1

Views: 570

Answers (2)

user12994274
user12994274

Reputation:

The ModelAdmin class has a method called get_queryset() where you can specify which objects someone will see.

from django.contrib import admin
from .models import Blog

@admin.register(Blog)
class BlogAdmin(admin.ModelAdmin):
    def get_queryset(self, request):
        queryset = super().get_queryset(request)
        return queryset.filter(author=request.user)

Upvotes: 0

enes islam
enes islam

Reputation: 1120

admin.py:

from django.contrib import admin
from .models import Blog

@admin.register(Blog)
class BlogAdmin(admin.ModelAdmin):

    def has_change_permission(self, request, obj=None):
        if obj is not None and obj.created_by != request.user:
            return False
        return True

    def has_delete_permission(self, request, obj=None):
        if obj is not None and obj.created_by != request.user:
            return False
        return True

Upvotes: 1

Related Questions