Dimitris Kougioumtzis Blog About technology

Django mixin for reusable absolute url method

Category Django

Posted on Oct. 10, 2017



Django mixin for reusable absolute url method


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from django.urls import reverse

class AbsoluteUrlMixin:
    '''
    Example:
        class Category(AbsoluteUrlMixin, models.Model):
            name = models.CharField(max_length=100)

            url_name = 'update'

        I use the convention as pattern:

            app_name.model_name.detail

    '''
    def get_absolute_url(self):
        kwargs = {}
        slug = hasattr(self, 'slug')
        url_name = hasattr(self, 'url_name')
        kwargs['pk'] = self.pk
        if not url_name:
            url_name = 'detail'
        if slug:
            kwargs['slug'] = self.slug
        return reverse('{}.{}.{}'.format(self._meta.app_label,
            self.__class__.__name__.lower(), url_name), kwargs=kwargs)

About

My name is Dimitris Kougioumtzis and i work as a Web developer at Rapidbounce Company

Elsewhere