Django:将请求直接(内联)传递到第二个 View

标签 django post view call form-submit

我正在尝试直接从另一个 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/

相关文章:

variables - Grails将变量从gsp传递到 Controller

python - 导入错误: No module named localflavor. br.br_states

python - 如何使用 Django 的 'with' 模板标签保存比较结果?

django-crm 安装

php - 使用 jQuery 填写表单元素,但值未传递到表单操作

php - (PHP + JQueryTools) Javascript 填充的输入字段在 POST 后返回 null

view - SAPUI5 添加自定义数据到 xmlView

python - 我的 css 和图像没有在 django 中显示

reactjs - 如何在 URL axios post 方法中使用 id 使用react?

mysql - 数据库 View 在 MySQL 中多久更新一次?