Django redirect from one page to another -
i working on project in django , i'm facing issue while redirecting 1 page on click of link. no matter i've tried, end having url like:
localhost:8080/page1/page2
instead of moving localhost:8080/page1
localhost:8080/page2
i've tried using httpresponseredirect(url)
the recommended way use {% url 'url-name' arg1 arg2 kwarg='foo' %}
in django template. shouldn't hardcode urls in template use url names.
more details: https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#url
the equivalent in python code django.utls.reverse
returns te absolute url or django.shortcuts.redirect
equivalent httpresponseredirect(reverse('url_name'))
https://docs.djangoproject.com/en/1.10/ref/urlresolvers/#django.urls.reverse
edit #1
use database pass items between views.
models.py
from django.db.models import model class item(model): # 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
<!-- html --> <ul> {% item in items %} <li> <a href="{% url 'details' item.id %}">item number {{ item.id }}</a> </li> {% endfor %} </ul> <!-- html -->
{% url ... %}
tag produces absolute url pattern named "details" , substitute part of address function argument. in addres, instead of (?p<item_id>[0-9]+)
, you'll have item id eg. /details/1/
. when click link, number 1
grabbed regex , passed function argument can take item database.
Comments
Post a Comment