views:

96

answers:

2

I have a modelform which has a user_id field that I have excluded from the form. This form is made into a modelformset. The reason I have the user field excluded is because it's not an editable value. I don't want that value to go to the HTML form where it can be tampered with by naughty user.

When I try to save this model formset, I get an error saying user_id can't be null. I need someway to add request.user to each form before I save that formset in the view. How can I do this? I know how to add the value to a single instance of a modelform, but I can't figure out how to do it with a formset.

+1  A: 

If you are not passing request.user to form, there is no direct way that you can get it in form's save method.

However there is a way, if you want user to be available directly at form's save method, from outside the context. Check out, http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser .

simplyharsh
A: 

When you are saving formset remeber to:

 if formset.is_valid():
                instances = formset.save(commit=False)
                for instance in instances:
                    instinace.user_id = request.user.id
                    inst.save()

You no need anything else ;-) BTW I dont't understand why save user id not user object ?

galuszkak