10

Can i print out a url /admin/manage/products/add of a certain view in a template?

Here is the rule i want to create a link for

(r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}),

I would like to have /manage/products/add in a template without hardcoding it. How can i do this?

Edit: I am not using the default admin (well, i am but it is at another url), this is my own

3 Answers 3

17

You can use get_absolute_url, but that will only work for a particular object. Since your object hasn't been created yet, it won't work in this case.

You want to use named URL patterns. Here's a quick intro:

Change the line in your urls.py to:

(r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}, "create-product"),

Then, in your template you use this to display the URL:

{% url create-product %}

If you're using Django 1.5 or higher you need this:

{% url 'create-product' %}

You can do some more powerful things with named URL patterns, they're very handy. Note that they are only in the development version (and also 1.0).

2
  • How can I call url in my view? E.g., return HttpResponseRedirect(...) where ... is the value of url create-product
    – user67416
    Jun 21, 2011 at 10:42
  • Don't forget to add name= in the urls.py, like so: (r'^view/$', 'view.function', name='hiya')
    – smilebomb
    Jun 11, 2014 at 19:25
2

If you use named url patterns you can do the follwing in your template

{% url create_object %}
0

The preferred way of creating the URL is by adding a get_absolute_url method to your model classes. You can hardcode the path there so you at least get closer to following the KISS philosophy.

You can go further by utilizing the permalink decorator that figures the path based on the urls configuration.

You can read more in the django documentation here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.