Django mixin for reusable absolute url method

Django -- Posted on Oct. 10, 2017

Django mixin for reusable absolute url method

              
                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)
                  
   
            

Related Posts