[Answer]-Url not Shortening in Django

1👍

You need an entry in urls.py for the shortened url schema:

url(r'^(?P<short_id>\w+)/$', 'artapp.views.artshort', name='artshort'),
url(r'^artlyf/(?P<mrts_id>\d+)/(?P<slug>[-\d\w]+)/$', 'artapp.views.artdetail', name='artdetail')

And methods on your model for getting both types of URL:

from django.core.urlresolvers import reverse

class Mrts(models.Model):
    # ...

    def get_absolute_url(self):
        return reverse('artdetail', args=[str(self.pk), self.slug])

    def get_short_url(self):
        return reverse('artshort', args=[self.get_short_id()])

A view for handling short url (this one just redirects to a full URL):

from django.shortcuts import redirect, get_object_or_404

def artshort(request, short_id):
    id = Mrts.decode_id(short_id)
    object = get_object_or_404(Mrts, pk=id)
    return redirect(object)

You can display shortened URL in a template like this (where post is a Mrts object):

{{ post.get_short_url }}

Leave a comment