[Django]-Django urls from models

4👍

This is a common problem, django provides the tools to do it using the reverse function

from django.core.urlresolvers import reverse

def get_edit_url(self):
    # assuming your app isn't namespaced
    return reverse('edit_articles', args=(self.pk,))
    # if your app was namespaced it would be something like 
    # reverse('articles:edit_articles')

0👍

I generally use reverse with model method:

from django.db import models
from django.core.urlresolvers import reverse

class MyModel(models.Model):
    ...
    def get_detail_url(self):
       return reverse('article-detail', args=(self.pk,))

    def get_list_url(self):
       return reverse('article-list')

This approach is more RESTful, detail_view will allow to get,delete,update an instance and list_view will allow to get list or eventually make bulk delete/update.

👤Zulu

0👍

You could use django-model-urls to do that automatically without even altering your model!

Using your example:

urls.py

url(r'^add/(?P<id>\d+)$', views.add_article, name='edit_articles'),

some template:

{{ url('edit_articles', article) }}

(Note that current version use jingo, raw Django template can use the 0.3.1 version)

👤vinyll

Leave a comment