在Django中,有没有一种好的方法可以动态选择要在基于类的视图中扩展哪个视图?
现在我有两个视图(更新和视图(如下,我想崩溃为1:
from django.views.generic import UpdateView, DetailView
from guardian.mixins import PermissionRequiredMixin
class MyUpdateView(PermissionRequiredMixin, UpdateView):
model = MyModel
permission_required = 'MyApp.change_mymodel'
template_name = "MyApp/update.html"
fields = ["name", "Type", "description"]
class MyDetailView(PermissionRequiredMixin, DetailView):
model = MyModel
permission_required = 'MyApp.view_mymodel'
template_name = "MyApp/view.html"
我想做的是有一个视图和一个url,当访问视图时,如果用户有更改权限,它应该使用UpdateView,如果他们有查看权限,则使用DetailView,如果两者都没有,则显示某种错误。
有办法做到这一点吗?
编辑:最终解决方案:
class CombinedView(PermissionRequiredMixin, DetailView, UpdateView):
model = MyModel
fields = ["name", "Type", "description"]
def get_required_permissions(self, request=None):
if (self.request.user).has_perm('MyApp.change_mymodel', self.get_object()):
return ['MyApp.change_mymodel']
return ['MyApp.view_mymodel']
def get_template_names(self):
if (self.request.user).has_perm('MyApp.change_mymodel', self.get_object()):
return ["MyApp/update.html"]
return ["MyApp/view.html"]
将get_template_names()
方法和get_required_permissions()
方式重写为
class CombinedView(PermissionRequiredMixin, DetailView, UpdateView):
model = MyModel
fields = ["name", "Type", "description"]
def get_required_permissions(self, request=None): # alternate to `permission_required`
if self.request.method == 'POST':
return ['MyApp.change_mymodel']
return ['MyApp.view_mymodel']
def get_template_names(self): # alternate to `template_name`
if self.request.method == 'POST':
return ["MyApp/update.html"]
return ["MyApp/view.html"]