Reputation: 3080
I using Django and a generic view "django.views.generic.create_update.create_object" I have a model form wich i pass to the generic view:
url(r'^add$', create_object, {'template_name':'tpl.html','form_class':MyModelForm,'post_save_redirect':'/'},name = 'add'),
I need to get current user in my ModelForm.save method.. But i can't find way to get it, please help me to find convinient way?
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?
In common way the question is - how can i accsess request params in forms passed to generic view.
Upvotes: 1
Views: 1396
Reputation: 3080
thnx this helps) I have some problems this syntax and _meta attr and i finished with this
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)
Upvotes: 1
Reputation: 11568
Look at that:
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)
So you have passed request to your class constructor. Or you can add it as attribute:
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)
Upvotes: 1
Reputation: 599600
You could probably hack something up to inject the request into the form instantiation, but why would you bother? Generic views are meant as a quick-and-easy solution to the basic requirements only. As soon as you start needing massive customisations, you might as well just write the actual view yourself. It's not very much code, after all.
Upvotes: 2