如何将附加属性发送给指定的方法?
问题描述:
我在互联网这样的解决方案发现:如何将附加属性发送给指定的方法?
def is_owner(self):
if self.request.user.profile_url == self.kwargs['profile_url']:
return True
else:
raise PermissionDenied
class CompanyProfileUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = CompanyProfile
template_name = 'profiles/create.html'
fields = ['user', 'name']
test_func = is_owner
谁能告诉我,怎么送附加价值的方法? 我想有这样的:
def is_owner(self, profile_type):
if profile_type == 'user':
if self.request.user.profile_url == self.kwargs['profile_url']:
return True
else:
raise PermissionDenied
else:
# some code
test_func = is_owner('user')
显然是行不通的,因为没有self
附: test_func
是UserPassesTestMixin
类的一种方法
答
您不能不更改UserPassesTestMixin
。更简单的解决方案可能是将kwarg
提供给urls.py文件中的视图,或者使用该类的其他profile_type
属性创建视图的新子类。
例如:
class CompanyProfileUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = CompanyProfile
template_name = 'profiles/create.html'
fields = ['user', 'name']
def test_func(self):
if self.kwargs['profile_type'] == 'user':
if self.request.user.profile_url == self.kwargs['profile_url']:
return True
else:
raise PermissionDenied
else:
# something
pass
urlpatterns += [
url('^$', views.CompanyProfileUpdateView.as_view(), name='update_user', kwargs={'profile_type': 'user'}),
url('^$', views.CompanyProfileUpdateView.as_view(), name='update_other', kwargs={'profile_type': 'other type'})
]
第二个选项:
class CompanyProfileUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = CompanyProfile
template_name = 'profiles/create.html'
fields = ['user', 'name']
profile_type = 'user'
def test_func(self):
if self.profile_type == 'user':
if self.request.user.profile_url == self.kwargs['profile_url']:
return True
else:
raise PermissionDenied
else:
# something
pass
class OtherProfileUpdateView(CompanyProfileUpdateView):
profile_type = 'other type'
的第一选项是可以接受的。有2个时刻hovewer:1)'def is_owner(self):'必须在类2之外)'url('^ $',views.CompanyProfileUpdateView.as_view(kwargs = {'profile_type':'user'}) ,name ='update_user'),'不起作用。我需要将其更改为'url('^ $',views.CompanyProfileUpdateView.as_view(),kwargs = {'profile_type':'user'},name ='update_user'),'谢谢。 – TitanFighter
根据文档,您应该简单地覆盖'test_func'而不是为其指定其他内容。 – schillingt
是的,我知道:)但我有9个检查所有者的视图,所以想避免代码重复和我在'django-imagestore'源文件中找到的分配技巧 - https://github.com/hovel/imagestore /blob/master/imagestore/views.py – TitanFighter