vijay shanker
vijay shanker

Reputation: 2673

How to pass variable in django but not as url parameter

I have this in urls.py:

urlpatterns = patterns('',
    url(r'^add_to_cart/(?P<app_label>\w+)/(?P<model_name>\w+)/(?P<obj_id>\d+)/$', AddToCart.as_view(), name='add-to-cart'),
    )

and i am using this to call AddToCart view in template:

{% for eg in eyeglasses %}
<p>{{eg}} <a href="{% url 'add-to-cart' eg|app_label eg|class_name  eg.pk %}" >Buy</a> </p>  
{% endfor %}

This ends up in having a url like this

"127.0.0.1/cart/add_to_cart/product/Sunglass/2/"

which i want to avoid. Is there any different way to pass these variables but without passing them as url parameters?

Upvotes: 1

Views: 1734

Answers (2)

Rohan
Rohan

Reputation: 53386

You can try passing them as querystring parameters instead of in url, so you can build url as

http://127.0.0.1/cart/add_to_cart?app_label=product&product=Sunglass&id=2

Build this in template as

{% for eg in eyeglasses %}
<p>{{eg}} <a href="{% url 'add-to-cart' %}?app_label={{eg.app_label}}&product={{eg.class_name}}&id={{eg.pk}} %}" >Buy</a> </p>  
{% endfor %}

In view you can get it as

def add_cart_view(request):
    ....
    product_name = request.GET.get('product')
    ...

Upvotes: 4

John Percival Hackworth
John Percival Hackworth

Reputation: 11531

Rather than having a list of links, create a form where you use buttons of type submit. For each button give it a value that you can retrieve from the request. When you submit the form set the method to post rather than get.

You may want to take a look part 4 of the Django tutorial.

Upvotes: 0

Related Questions