Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Print url of view without hardcoding the url

Tags:

python

django

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

like image 322
Josh Hunt Avatar asked Sep 06 '08 02:09

Josh Hunt


2 Answers

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).

like image 128
Harley Holcombe Avatar answered Sep 20 '22 17:09

Harley Holcombe


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

{% url create_object %}
like image 26
Peter Hoffmann Avatar answered Sep 17 '22 17:09

Peter Hoffmann