views:

685

answers:

2

I know how to set initial values to a form from the view. But how do I go about letting a generic view set initial values to a form? I can write a wrapper view for the generic view, but I still have no access to the form object instantiation.

The specific goal I'm trying to achieve is to have a user create a new object, using the create_object generic view. However, I'd like to set a field of the object 'user' to the currently logged in user, which is only accessible as request.user. How can the form be initialized to have this field?

Edit: I came across __new__. Could this call its own constructor with some default arguments?

Many thanks.

+3  A: 

Unfortunately, you cannot achieve this behavior through Django's create_object generic view; you will have to write your own. However, this is rather simple.

To start off, you must create a new form class, like this:

from django import forms
class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel  # model has a user field

Then you would be able to create a view like this:

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required

@login_required
def create_mymodel(request):
    if request.method == 'POST':
        # Get data from form
        form = MyForm(request.POST)
        # If the form is valid, create a new object and redirect to it.
        if form.is_valid():
            newObject = form.save()
            return HttpResponseRedirect(newObject.get_absolute_url())
    else:
        # Fill in the field with the current user by default
        form = MyForm(initial={'user': request.user})
    # Render our template
    return render_to_response('path/to/template.html',
        {'form': form},
        context_instance=RequestContext(request))
Quartz
Thanks. I knew about this already, but the generic view is so tantalizing that it couldn't work with initial values.
MTsoul
I agree: the generic views are great, but if you want to set defaults, it's a nightmare. And I whole-heartedly agree with Carl Meyer's post.
Quartz
+2  A: 

You could do this in a generic view wrapper by dynamically constructing a form class and passing it to the generic view, but that cure is probably worse than the disease. Just write your own view, and wait eagerly for this to land.

Carl Meyer