[英]Django: Show different content based on User
I'd like to create a school management system for my personal project. 我想为我的个人项目创建一个学校管理系统。
Let's say there is an Admin for every School. 假设每个学校都有一个管理员。 But there is some Admin that can manage more than one schools, and they can switch between schools to manage each school.
但是有些管理员可以管理多于一所学校,并且他们可以在学校之间切换以管理每所学校。
I've thought one way to do it, by using different URL path eg. 我想过一种方法,例如使用不同的URL路径。
urlpatterns = [
url(schools/<int:pk>/, SchoolView.as_view()),
]
Is there a way so I do not separate by using different URL path for each schools? 有没有办法让我不为每个学校使用不同的URL路径而分开? So, each Admin get similar URL path, but the view render or filter to use different school, based on the Admin.
因此,每个管理员都将获得相似的URL路径,但视图将基于Admin呈现或过滤以使用不同的学校。
But I don't really know how to do that? 但是我真的不知道该怎么做吗? Can I get an advice how to do it.
我可以征求意见吗。 Many thanks!
非常感谢!
Every view function accepts a request
parameter, so wherever you define your view function it would probably look like: 每个视图函数都接受一个
request
参数,因此无论您在何处定义视图函数,它都可能看起来像:
from django.shortcuts import render
def my_view(request):
#you can check user here with request.user
#example
if request.user.is_superuser:
return render('your_template_for_admin.html', {})
return render('your_template_for_basic_user.html', {})
EDIT: If you're using a class based view then you can override it's get method like this: 编辑:如果您使用基于类的视图,则可以覆盖它的get方法,如下所示:
from django.shortcuts import render
from django.views import View
class MyView(View):
def get(self, request, *args, **kwargs):
#here you can access the request object
return render('template.html', {})
Edit based on comment : You can use get_context_data() instead of get()
as @Daniel Roseman stated in comments. 根据评论进行编辑 :您可以使用get_context_data()代替@Daniel Roseman在评论中指出的
get()
。
from django.views import View
class MyView(View):
def get_context_data(self, **kwargs):
#example code assuming that we have a relation between schools and admin A
context = super().get_context_data(**kwargs)
context['schools'] = School.objects.filter(admin_id=self.request.user__id)
return context
And then you can use schools
queryset in your template. 然后,您可以在模板中使用
schools
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.