将使用捕获的 url 参数创建的表单传递给通用 django 视图?
这看起来应该是显而易见的,但我却找不到解决方案。通常我只会编写一个简单的视图函数,它会填充适当的表单并将其传递给视图,但解决方案感觉非常接近..
我有一个表单。我想使用在 url 中捕获的 object_id
实例化此表单,然后使用 extra_context
参数将其发送到我的模板。
我有这样的东西:
class AddProductForm(forms.Form):
product = forms.IntegerField()
quantity = forms.IntegerField()
还有这样的:
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'),
有没有办法用捕获的 object_id
值替换上面的
? (也许传入 extra_context
的一个聪明的可调用函数可以为我制作表单?)
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+)/
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?)
,
'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?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
恐怕你不能在 urlconf 中这样做。您提供的任何可调用对象都不能接受任何参数,因此您将无法获取
?P
的值。不过,您可以在自己的视图中重复使用通用视图,以减少必须编写的样板文件数量:
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: