Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate urls in django

In Django's template language, you can use {% url [viewname] [args] %} to generate a URL to a specific view with parameters. How can you programatically do the same in Python code?

What I need is to create a list of menu items where each item has name, URL, and an active flag (whether it's the current page or not). This is because it will be a lot cleaner to do this in Python than the template language.

like image 578
Staale Avatar asked Sep 04 '08 07:09

Staale


People also ask

What is the use of urls py in Django?

A request in Django first comes to urls.py and then goes to the matching function in views.py. Python functions in views.py take the web request from urls.py and give the web response to templates. It may go to the data access layer in models.py as per the queryset.

How can I get current URL in Django?

Run the following command to start the Django server. Execute the following URL from the browser to display the domain name of the current URL. The geturl1() function will be called for this URL that will send the domain name to the index. html file.

What is Django urls path?

The path function is contained with the django. urls module within the Django project code base. path is used for routing URLs to the appropriate view functions within a Django application using the URL dispatcher.


2 Answers

If you need to use something similar to the {% url %} template tag in your code, Django provides the django.core.urlresolvers.reverse(). The reverse function has the following signature:

reverse(viewname, urlconf=None, args=None, kwargs=None) 

https://docs.djangoproject.com/en/dev/ref/urlresolvers/

At the time of this edit the import is django.urls import reverse

like image 141
Peter Hoffmann Avatar answered Sep 29 '22 00:09

Peter Hoffmann


I'm using two different approaches in my models.py. The first is the permalink decorator:

from django.db.models import permalink  def get_absolute_url(self):      """Construct the absolute URL for this Item."""     return ('project.app.views.view_name', [str(self.id)]) get_absolute_url = permalink(get_absolute_url) 

You can also call reverse directly:

from django.core.urlresolvers import reverse  def get_absolute_url(self):      """Construct the absolute URL for this Item."""     return reverse('project.app.views.view_name', None, [str(self.id)]) 
like image 34
Garth Kidd Avatar answered Sep 28 '22 23:09

Garth Kidd