django:如何在 ModelForm 中访问当前请求用户? [英] django: how to access current request user in ModelForm?

查看:23
本文介绍了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?

推荐答案

您可以将用户对象作为额外参数传递给表单构造函数.

you can pass the user object as an extra argument in the form constructor.

例如

f = MyForm(user=request.user)

构造函数看起来像:

class MyForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
         self.user = kwargs.pop('user',None)
         super(MyForm, self).__init__(*args, **kwargs)

然后根据需要在 clean_XX 表单中使用用户

and then use user in the clean_XX forms as you wish

这篇关于django:如何在 ModelForm 中访问当前请求用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆