我想为每个具有不同权限的用户显示不同的内容,我试图从ModelForm类的init()
函数中获取当前用户,但失败
下面的代码是我当前在ModelForm中的init()
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user',None)
super(MyForm, self).__init__(*args, **kwargs)
但是self.user仅在表单发送后才起作用,例如在is_valid()
函数或clean_data()
函数中
我总是在self.user
中获得init()
的“无”值
我是否应该继续尝试在ModelForm init()
中获取当前用户,
还是有更好的方法来实现这种功能?
答案 0 :(得分:2)
您需要从View发送此数据。例如,在Generic Class Based Edit View中,您可以使用get_form_kwargs():
class YourView(FormView):
form_class = YourForm
...
def get_form_kwargs(self):
kwargs = super(YourView, self).get_form_kwargs()
kwargs['user'] = self.request.user
return kwargs
在其他情况下,通过传递已知参数user
来初始化表单:
def some_view(request):
form = YourForm(request.POST, user=request.user)
答案 1 :(得分:1)
f = MyForm(user=request.user) // where you are calling the form in the view
,构造函数将如下所示:
class MyForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user',None)
super(MyForm, self).__init__(*args, **kwargs)
答案 2 :(得分:-2)
在项目文件夹中创建一个新文件,并将其命名为middleware.py:
from __future__ import absolute_import, division, print_function
try:
from threading import local
except ImportError:
from django.utils._threading_local import local
_thread_locals = local()
def get_current_request():
""" returns the request object for this thread """
return getattr(_thread_locals, "request", None)
def get_current_user():
""" returns the current user, if exist, otherwise returns None """
request = get_current_request()
if request:
return getattr(request, "user", None)
class ThreadLocalMiddleware(object):
""" Simple middleware that adds the request object in thread local stor age."""
def process_request(self, request):
_thread_locals.request = request
def process_response(self, request, response):
if hasattr(_thread_locals, 'request'):
del _thread_locals.request
return response
然后,配置您的设置文件:
settings.py:
MIDDLEWARE = [ ... “ YOUR_PROJECT_NAME.middleware.ThreadLocalMiddleware”, ]
在要获得当前用户的任何地方使用函数get_current_user()。 示例 models.py:
from YOUR_PROJECT_NAME.middleware import get_current_user
...
Class SomeModel(models.Model):
...
def some_method(self):
current_user = get_current_user()
....