首页 > 解决方案 > Django:根据用户显示不同的内容

问题描述

我想为我的个人项目创建一个学校管理系统。

假设每所学校都有一个管理员。但是有一些管理员可以管理多所学校,他们可以在学校之间切换来管理每所学校。

我想到了一种方法,例如使用不同的 URL 路径。

urlpatterns = [
    url(schools/<int:pk>/, SchoolView.as_view()),
]

有没有办法让我不通过为每所学校使用不同的 URL 路径来分开?因此,每个 Admin 获得相似的 URL 路径,但视图渲染或过滤器使用不同的学校,基于 Admin。

但我真的不知道该怎么做?我可以得到一个建议如何做到这一点。非常感谢!

标签: pythondjangopermissionsdjango-templatesdjango-views

解决方案


每个视图函数都接受一个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', {})

编辑:如果您使用的是基于类的视图,那么您可以覆盖它的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', {})

根据评论进行编辑:您可以使用get_context_data()而不是评论中get()所述的@Daniel Roseman。

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

然后您可以schools在模板中使用查询集。


推荐阅读