本文介绍了django:如何访问ModelForm中的当前请求用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的ModelForm的实现中,我想根据当前用户是超级用户执行不同类型的验证检查。如何访问当前请求用户?
解决方案
您可以将用户对象作为额外的参数传递给表单构造函数。 / p>
例如
f = MyForm(user = request.user)
,构造函数将如下所示:
class MyForm(forms.ModelForm):
def __init __(self,* args,** kwargs):
self.user = kwargs.pop('user'没有)
super(MyForm,self).__ init __(* args,** kwargs)
然后根据需要使用clean_XX表单中的用户
In my implementation of ModelForm, I would like to perform different types of validation checks based on whether current user is superuser. How can I access the current request user?
解决方案
you can pass the user object as an extra argument in the form constructor.
e.g.
f = MyForm(user=request.user)
and the constructor will look like:
class MyForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user',None)
super(MyForm, self).__init__(*args, **kwargs)
and then use user in the clean_XX forms as you wish
这篇关于django:如何访问ModelForm中的当前请求用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!