开发者

Django url handling?

After decoupling url file to our app we are facing problem:

Example:

http://www.oursite.com/ourprefix/xyz/wsz

  1. How to handle urls in template ( to accomodate for any prefix(ourprefix) in url)
  2. How to do HttpResponseRedirect with开发者_开发技巧out hard-coded urls (also outprefix problem is present here)


Use named urls in urls.py.

  1. Use the {% url name %} template tag. It will insert the correct path.
  2. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜