Django中的UserPassesTestMixin如何工作? [英] How does UserPassesTestMixin in django work?
问题描述
views.py
class ProfileEdit(UserPassesTestMixin,UpdateView):
model = User
form_class = ProfileForm
template_name =profile / profile_new.html
def test_func(self):
x = self.request.user.id
print(x)
y = self.kwargs ['pk']
print(y)
a = True
b = False
如果self.request.user.id == self.kwargs [ 'pk']:
print(a)
else:
print(b)
返回重定向('/ login /')
,您可以在输出图像中看到测试条件实际上满足..但是为什么如果它是真的则打印False。
来自请求对象中的用户的用户标识是一个整数,而 self.kwargs ['pk']
是一个字符串,除非你做一些事情。如果您打印 repr()
的值,您会看到差异,因为这个字符串会在其周围引用引号,因为它是从url路径中提取出来的,该路径本身是一个字符串。 / p>
尝试使用 int()
在比较 self.request.user.id之前进行转换== int(self.kwargs ['pk'])
。不要忘记抓住 ValueError
,如果有可能看起来不像整数。
views.py
class ProfileEdit(UserPassesTestMixin, UpdateView):
model = User
form_class = ProfileForm
template_name="profile/profile_new.html"
def test_func(self):
x = self.request.user.id
print (x)
y = self.kwargs['pk']
print (y)
a = True
b = False
if self.request.user.id == self.kwargs['pk']:
print (a)
else:
print (b)
return redirect ('/login/')
as you can see in the output image the test condition actually satisfies.. but why does it print "False" if it's true.
The user id coming from the user in the request object is an integer, while the self.kwargs['pk']
is a string unless you do something about it. You'd see the difference if you printed repr()
of the values because the string would have quotes around it because it's extracted from the url path which itself is a string.
Try casting it with int()
before comparing like self.request.user.id == int(self.kwargs['pk'])
. Don't forget to catch ValueError
if there's a possibility of it not looking like an integer.
这篇关于Django中的UserPassesTestMixin如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!