开发者

Django: Passing a request directly (inline) to a second view

I'm trying to call a view directly from another (if this is at all possible). I have a 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.

Then I have a 2nd view, that queries the DB for the product data and should call the first one.

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

Since the second one needs to add the product as the first view does it I was wondering if I could just call the first view from the second one.

What I'm aiming for is just passing through the request object to the second view and return the obtained response object in turn back to the client.

Any help greatly appreciated, critism as well if this is a bad way to do it. But then some pointers .. to avoid DRY-ing.

Thanx!

Gerard.


My god, what was I thinking. This would be the cleanest solution ofcourse:

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]) )


A view is a regular python method, you can of course call one from another giving you pass proper arguments and handle the result correctly (like 404...). Now if it is a good practice I don't know. I would myself to an utiliy method and call it from both views.


If you are fine with the overhead of calling your API through HTTP you can use urllib to post a request to your product_add request handler.

As far as I know this could add some troubles if you develop with the dev server that comes with django, as it only handles one request at a time and will block indefinitely (see trac, google groups).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜