views:

169

answers:

1

This seems like it should be obvious, but the solution is eluding me. Normally I would just write a simple view function which would populate an appropriate form and pass it along to the view, but the solution feels so close ..

I have a form. I want to instantiate this form using an object_id that I've captured in the url, then send it through to my template using the extra_context parameter.

I have something like this:

class AddProductForm(forms.Form): 
    product = forms.IntegerField()
    quantity = forms.IntegerField()

and this:

url(r'^products/(?P<object_id>\d+)/$', 
    'django.views.generic.list_detail.object_detail',
    {'queryset': Product.objects.all(),
    'extra_context': {'form': AddProductForm({'product': <what?>, 'quantity': 1})},
    name='product_detail'),

Is there a way to replace <what?> above with the captured value of object_id? (Maybe a clever callable passed in extra_context could make the form for me?)

+6  A: 

I'm afraid you can't do that in your urlconf. Any callables you supply can not accept any arguments, so you won't be able to get the value of ?P<object_id>.

You can however re-use the generic view in your own view to cut down on the amount of boilerplate you have to write:

from django.views.generic.list_detail import object_details
from your.forms import AddProductForm
from your.models import Product

def about_pages(request, object_id=None):
    qs = Product.objects.all()
    f = AddProductForm({'product':object_id,'quantity':1})
    return object_details(request,queryset=qs,extra_context={'form':f},template='yourtemplate.html')
Wogan
+1 Thanks, this is essentially what I did (ultimately I had to add extra fields to my form, so something like this was necessary anyway). I am left wondering what people use callables for in extra_context though.
Seth
See the generic views documentation on adding extra context - basically it is for additional querysets you may want to use in your templates.
Wogan