Marius Bogdan
Marius Bogdan

Reputation: 434

django urls from models

I have the following model:

class Articles(models.Model):
    status = models.CharField(choices=STATUSES, max_length=10, default='online')
    categ = models.ForeignKey(ArticlesCategories)
    title = models.CharField(max_length=64)
    content = models.TextField()

    def get_edit_url(self):
       return '/articles/add/%d' % self.pk

    edit_url = property(get_edit_url)

    def __unicode__(self):
        return self.title

    class Meta:
        db_table = 'articles'

and the url route:

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

How do I have to edit the "get_edit_url" function so the url for edit article to be generated dynamically and to be able to change the path only from urls.py ?

Thank you

Upvotes: 3

Views: 5301

Answers (3)

vinyll
vinyll

Reputation: 11439

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)

Upvotes: 0

Zulu
Zulu

Reputation: 9285

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.

Upvotes: 0

dm03514
dm03514

Reputation: 55972

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

Upvotes: 4

Related Questions