开发者

Pass a form created with captured url parameters to a generic django view?

开发者 https://www.devze.com 2022-12-14 17:40 出处:网络
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

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): 
    pr开发者_开发问答oduct = 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?)


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')
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号