我正在尝试直接从另一个 View 调用 View (如果可能的话)。我有一个看法:
def product_add(request, order_id=None):
# Works. Handles a normal POST check and form submission and redirects
# to another page if the form is properly validated.
然后我有第二个 View ,它在数据库中查询产品数据,并且应该调用第一个 View 。
def product_copy_from_history(request, order_id=None, product_id=None):
product = Product.objects.get(owner=request.user, pk=product_id)
# I need to somehow setup a form with the product data so that the first
# view thinks it gets a post request.
2nd_response = product_add(request, order_id)
return 2nd_response
由于第二个 View 需要像第一个 View 一样添加产品,我想知道是否可以从第二个 View 中调用第一个 View 。
我的目标只是将请求对象传递到第二个 View ,并将获得的响应对象依次返回给客户端。
非常感谢任何帮助,如果这是一个不好的方法,也请批评。但接下来是一些避免 DRY-ing 的提示。
谢谢!
杰拉德。
最佳答案
天哪,我在想什么。这当然是最干净的解决方案:
def product_add_from_history(request, order_id=None, product_id=None):
""" Add existing product to current order
"""
order = get_object_or_404(Order, pk=order_id, owner=request.user)
product = Product.objects.get(owner=request.user, pk=product_id)
newproduct = Product(
owner=request.user,
order = order,
name = product.name,
amount = product.amount,
unit_price = product.unit_price,
)
newproduct.save()
return HttpResponseRedirect(reverse('order-detail', args=[order_id]) )
关于Django:将请求直接(内联)传递到第二个 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1893456/