Reputation: 65
I created a custom admin view in django for one of the models. But the url is available to anyone who is not logged in. I want only the staff user to be able to access the url.
from django.contrib import admin
from django.urls import path
from django.shortcuts import render, redirect
from .models import Question
from django.contrib.admin.views.decorators import staff_member_required
class QuestionAdmin(admin.ModelAdmin):
list_display = ('question_text', 'pub_date') # Your model fields
def get_urls(self):
urls = super().get_urls()
new_urls = [path('upload-csv/',self.upload_csv),]
return new_urls + urls
@staff_member_required
def upload_csv(self,request):
return render(request,"admin/csv_upload.html")
admin.site.register(Question,QuestionAdmin)
I tried adding the staff_member_required
decorator but there is an error message saying 'QuestionAdmin' object has no attribute 'user'
Upvotes: 0
Views: 85
Reputation: 65
For making the view restricted just to stuff_member you do not have to add the decoration. You can use admin_site.admin_view
as follows:
from django.contrib import admin
from django.urls import path
from django.shortcuts import render, redirect
from .models import Question
class QuestionAdmin(admin.ModelAdmin):
list_display = ('question_text', 'pub_date') # Your model fields
def get_urls(self):
urls = super().get_urls()
new_urls = [path('upload-csv/', self.admin_site.admin_view(self.upload_csv)),]
return new_urls + urls
def upload_csv(self,request):
return render(request,"admin/csv_upload.html")
admin.site.register(Question,QuestionAdmin)
Upvotes: 0
Reputation: 59
You should add in logic referring to your user- here I have identified them as staffuser but you can replace with the name you have used for your staff user.
For your else: I would redirect to somewhere a non staff member should be looking!
@staff_member_required
def upload_csv(self, request):
if request.user.get_staffuser():
return render(request,"admin/csv_upload.html")
Upvotes: 1