我使用Django和通用视图“django.views.generic.create_update.create_object” 我有一个模型表单,我传递给通用视图:
url(r'^add$', create_object, {'template_name':'tpl.html','form_class':MyModelForm,'post_save_redirect':'/'},name = 'add'),
我需要在我的ModelForm.save方法中获取当前用户.. 但我找不到方法,请帮我找到方便的方法?
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
def save(self,*a,**b):
MyModel.save(user=request.user) #how can i get here request.user?
class Meta:
model = MyModel
def save(self,*a,**b):
MyModel.save(user=request.user) #how can i get here request.user?
通常的问题是 - 如何在传递给通用视图的表单中使用请求参数。
答案 0 :(得分:2)
你可能会破解一些东西将请求注入到表单实例化中,但为什么你会烦恼?通用视图仅作为基本要求的快速简便解决方案。一旦你开始需要大规模的自定义,你也可以自己编写实际的视图。毕竟,这不是很多代码。
答案 1 :(得分:1)
看那个:
url(r'^add$', create_object_with_request, {'template_name':'tpl.html','form_class':MyModelForm,'post_save_redirect':'/'},name = 'add'),
,
def create_object_with_request(request, *args, **kwargs):
def inject_request(fun):
def helper(*args, **kwargs):
return fun(*args, request=request, **kwargs)
return helper
kwargs['form_class'] = inject_request(kwargs['form_class'])
return create_object(request, *args, **kwargs)
所以你已经将请求传递给了你的类构造函数。或者您可以将其添加为属性:
def create_object_with_request(request, *args, **kwargs):
def inject_request(fun):
def helper(*args, **kwargs):
res = fun(*args, **kwargs)
res.request = request
return res
return helper
kwargs['form_class'] = inject_request(kwargs['form_class'])
return create_object(request, *args, **kwargs)
答案 2 :(得分:1)
thnx这有帮助)我有一些问题这个语法和_meta attr我完成了这个
def create_object_with_request(request, *args, **kwargs):
def inject_request(fun):
def helper(*args, **kwargs):
finst = fun(*args, **kwargs)
finst.request = request
return finst
helper._meta = fun._meta
return helper
kwargs['form_class'] = inject_request(kwargs['form_class'])
return create_object(request,*args, **kwargs)
def inject_request(fun):
def helper(*args, **kwargs):
finst = fun(*args, **kwargs)
finst.request = request
return finst
helper._meta = fun._meta
return helper
kwargs['form_class'] = inject_request(kwargs['form_class'])
return create_object(request,*args, **kwargs)