python - Django:根据用户显示不同的内容
问题描述
我想为我的个人项目创建一个学校管理系统。
假设每所学校都有一个管理员。但是有一些管理员可以管理多所学校,他们可以在学校之间切换来管理每所学校。
我想到了一种方法,例如使用不同的 URL 路径。
urlpatterns = [
url(schools/<int:pk>/, SchoolView.as_view()),
]
有没有办法让我不通过为每所学校使用不同的 URL 路径来分开?因此,每个 Admin 获得相似的 URL 路径,但视图渲染或过滤器使用不同的学校,基于 Admin。
但我真的不知道该怎么做?我可以得到一个建议如何做到这一点。非常感谢!
解决方案
每个视图函数都接受一个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
在模板中使用查询集。
推荐阅读
- python - Python Tkinter - 在不创建新实例的情况下在屏幕上绘制形状
- node.js - 使用 Typescript 处理 Express 类中的错误
- java - Android (JAVA) - 在每天上午 9:00 的特定时间调用 REST API
- c# - 错误 MSB4086:尝试对“$(MSBuildAssemblyVersion)”进行数字比较
- python - 属性更新后的对象事件
- javascript - jquery 'show' + 'animate' 仅适用于第一次点击
- javascript - 如果正值和负值,javascript突出显示表格单元格值
- jquery - 如何将ajax请求发送到laravel控制器公共功能
- javascript - Node/Express:如何分离服务器端和客户端 javascript?
- c# - c#中声明对象的方法