tags:

views:

80

answers:

2

Let's say trying to use django.views.generic.create_update.create_object to allow the user to a blog entry instance. On the Entry model, there is a required field for the user, that I don't want to show up as an editable field on the blog entry form. So, I would include it into the EntryForm.Meta.exclude tuple.

Where should I set the value for the user property on the resulting model instance? Would I have to stop using the create_object generic view and write my own?

+2  A: 

I don't think you can accomplish this with generic views, they don't have much in the way of post-processing data. Thankfully, it isn't hard to write your own view to do the same thing.

(Adapted from http://www.djangobook.com/en/1.0/chapter07/)

from yourmodel.forms import EntryForm

def create_entry(request):
    if request.method == 'POST':
        form = EntryForm(request.POST)
        if form.is_valid():
            entry = form.save(commit = false)
            entry.author = request.user.username
            entry.save()
            return HttpResponseRedirect('/create_entry/thanks/')
    else:
        form = EntryForm()
    return render_to_response('/path/to/template.html', {'form' : form, ...}, ...)

Of course you'll have to use your own names and such, but that's the logic. Basically you're checking if a form has been submitted, and if so get the Entry, add in a username, and save it as usual. As far as differences from the generic create_object view are concerned, instead of specifying things such as the post_redirect_url in the view call, you give them directly. Check the docs of render_to_response and HttpResponseRedirect for more info.

sykora
A: 

There is one little problem with sykora's solution: if the form is invalid you will get an error because form won't be set (outside of the scope of the if statement).

Here's a slightly better version:

from yourmodel.forms import EntryForm

def create_entry(request):
    form = EntryForm()
    if request.method == 'POST':
        form = EntryForm(request.POST)
        if form.is_valid():
            entry = form.save(commit = false)
            entry.author = request.user.username
            entry.save()
            return HttpResponseRedirect('/create_entry/thanks/')
    return render_to_response('/path/to/template.html', {'form' : form, ...}, ...)
David