Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Form Preview - Adding the User to the Form before save

Tags:

django-forms

class RegistrationFormPreview(FormPreview):
    preview_template    = 'workshops/workshop_register_preview.html'
    form_template       = 'workshops/workshop_register_form.html'

    def done(self, request, cleaned_data):
        # Do something with the cleaned_data, then redirect
        # to a "success" page. 
        # data = request.POST.copy()
        # data['user_id'] = u'%s' % (request.user.id)
        # cleaned_data['user'] = u'%s' % (request.user.id)
        #f = self.form(cleaned_data)
        #f = self.form(data)
        #f.user = request.user


        f = self.form(request.POST)
        f.save()

        pdb.set_trace()
        return HttpResponseRedirect('/register/success')

As you can see, I've tried a few ways, and that have been commented out. The task is apparently simple: Add the user from request to the form before save, and then save.

What is the accepted, working method here?

like image 522
Antonius Common Avatar asked Mar 09 '09 10:03

Antonius Common


1 Answers

If the user can't be modified, I would say it shouldn't even be included in the form in the first place.

Either way, using the commit argument to prevent the resulting object being saved immediately should work (assuming FormPreview uses ModelForm):

obj = form.save(commit=False)
obj.user = request.user
obj.save()
like image 166
Jonny Buchanan Avatar answered Nov 25 '22 19:11

Jonny Buchanan