Django url handling?
After decoupling url file to our app we are facing problem:
Example:
http://www.oursite.com/ourprefix/xyz/wsz
- How to handle urls in template ( to accomodate for any prefix(ourprefix) in url)
- How to do HttpResponseRedirect with开发者_开发技巧out hard-coded urls (also outprefix problem is present here)
Use named urls in urls.py
.
- Use the
{% url name %}
template tag. It will insert the correct path. - Use
reverse('name', **kwargs)
for the redirect.
an example:
in proj/urls.py:
patterns = patterns('',
(r'^prefix/', include('proj.app.urls') ),
)
in proj/app/urls.py:
patterns = patterns('',
url(r'object/^(?P<pk>\d+)/edit/', edit_object_view, name="edit"),
)
in proj/app/views.py:
return HttpResponseRedirect(reverse('app:edit', {'pk':pk}))
in proj/app/templates/app/my_template.py:
<a href="{% url app:edit pk=pk %}"> <!-- generates /prefix/object/123/edit/ -->
If I understand you right, you want to resolve a particular view to a URL inside the template?
You should use the url-reverse method in Django. See here.
1) For the template, you can use:
<a href="/path/to/{{prefix}}/xyz"> Link </a>
Where the "prefix" is a variable set in your Context that you pass to the template. You can also dynamically pick the right URL:
{% url application.views.viewfunc parameter1 parameter2 %}
See here for more details.
2) So to HttpResponseRedirect, you can do:
HttpResponseRedirect(reverse(your_view_function))
It also accepts parameters.
精彩评论