Django redirect from one page to another

Venu Saini picture Venu Saini · Aug 8, 2016 · Viewed 9.6k times · Source

I am working on a project in Django and I'm facing an issue while redirecting from one page to another on the click of a link. No matter what all I've tried, I end up having a url like:

localhost:8080/page1/page2

instead of moving from localhost:8080/page1 to localhost:8080/page2

I've tried by using HttpResponseRedirect(url)

Answer

warownia1 picture warownia1 · Aug 8, 2016

The recommended way is to use {% url 'url-name' arg1 arg2 kwarg='foo' %} in django template. You shouldn't hardcode urls in your template but use url names.
More details: https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#url

The equivalent in python code is django.utls.reverse which returns te absolute url or django.shortcuts.redirect which is equivalent to HttpResponseRedirect(reverse('url_name'))
https://docs.djangoproject.com/en/1.10/ref/urlresolvers/#django.urls.reverse

EDIT #1

Use database to pass items between views.

models.py

from django.db.models import Model

class Item(Model):
    # your model fields

views.py

def list_view(request):
    items = Item.objects.all()
    context = {'items': items}
    return render(request, 'list_template.html', context)

def details_view(request, item_id):
    item = Item.objects.get(id=item_id)
    context = {'item': item}
    return render(request, 'details_template.html', context)

urls.py

urlpatterns = [
    url(r'^/list/$', views.list_view, name='list')
    url(r'^/details/(?P<item_id>[0-9]+)/$', views.details_view, name='details'),
]

list_template.html

<!-- your html -->
<ul>
{% for item in items %}
    <li>
    <a href="{% url 'details' item.id %}">item number {{ item.id }}</a>
    </li>
{% endfor %}
</ul>
<!-- your html -->

{% url ... %} tag produces absolute url to pattern named "details" and substitute part of the address with function argument. In the addres, instead of (?P<item_id>[0-9]+), you'll have item id eg. /details/1/. When you click the link, number 1 is grabbed by regex and passed to the function argument where you can take your Item from the database.