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?
CodePudding user response:
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
CodePudding user response:
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)