开发者

Django url handling?

开发者 https://www.devze.com 2023-03-08 12:23 出处:网络
After decoupling url file to our app we are facing problem: Example: http://www.oursite.com/ourprefix/xyz/wsz

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

精彩评论

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