views:

205

answers:

3

Hi all,

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.

A: 

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.

By utility method you mean write a seperate helper function?
GerardJP
A: 

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

tosh
Good point on the overhead. Thanx!
GerardJP
+1  A: 

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