django:如何在 ModelForm 中访问当前请求用户?
在我的 ModelForm 实现中,我想根据当前用户是否是超级用户来执行不同类型的验证检查。如何访问当前请求用户?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您使用基于类的视图 (CBV),则在表单构造函数(例如在
get_forms_class
中)或form_class
中传递额外参数将不起作用,因为<表格>将显示对象不可调用
。CBV 的解决方案是使用
get_form_kwargs()
,例如:views.py:
forms.py:
If you're using Class Based Views (CBVs) then passing an extra argument in the form constructor (e.g. in
get_forms_class
) or inform_class
will not work, as<form> object is not callable
will be shown.The solution for CBVs is to use
get_form_kwargs()
, e.g.:views.py:
forms.py:
您可以将用户对象作为表单构造函数中的额外参数传递。
例如
,构造函数将如下所示:
然后根据需要在 clean_XX 表单中使用 user
you can pass the user object as an extra argument in the form constructor.
e.g.
and the constructor will look like:
and then use user in the clean_XX forms as you wish
我的一个小补充是,
我有一个要求,其中表单的模型选择字段之一依赖于
request.user
,我花了一段时间才明白。这个想法是,
您需要在模型表单类中有一个
__init__
方法,并且您可以从
__init__
方法的参数访问请求
或其他参数,queryset
代码示例
如您所见,
lists
变量依赖于当前用户,该用户可通过request
对象获得,因此我们设置了queryset
的字段为 null,稍后从构造函数动态分配。查看上面代码中语句的顺序
您可以从视图文件中传递用户变量
,或者使用其他 POST、FILE 数据,如下所示
My small addition,
I had a requirement where one of the model choice fields of the form is dependent on the
request.user
, and it took a while to take my head around.The idea is that
you need to have a
__init__
method in the model form class,and you access the
request
or other parameters from the arguments of the__init__
method,queryset
of the required fieldcode sample
as you can see, the
lists
variable is dependent on the current user, which is available viarequest
object, so we set thequeryset
of the field as null, and its assigned dynamically from the constructor later.Take a look into the order of the statements in the above code
you can pass the user variable like this from the view file
or with other POST, FILE data like below
您可以使用实例本身的实例属性来引用用户对象。
前任;
self.instance.user
You may reference the user object using the instance attribute within the instance it self.
Ex;
self.instance.user
这对我有用,当我没有在 get_context_data 中显式发送上下文中的表单时:
views.py
form.py
当在 get_context_data 中显式发送表单时,我们可以使用,这是 forms.Form :
views.py
类 MyView(FormView):
模型=我的模型
form_class = MyForm
forms.py
This worked for me, when I am not sending form in context explicitly in get_context_data:
views.py
form.py
When sending form explicitly in get_context_data we can use and this is forms.Form :
views.py
class MyView(FormView):
model = MyModel
form_class = MyForm
forms.py