Django中的URL不缩短

时间:2013-10-13 13:48:29

标签: python django django-models django-views

我想获取特定页面网址并自动缩短网址,并将其显示给用户。在编写以下代码后,它没有正确缩短。

Page url

127.0.0.1:8000/artlyf/1/topman

缩短后的网页网址

127.0.0.1:8000/artlyf/1/topman/b 

Models.py

_char_map = string.ascii_letters+string.digits

def index_to_char(sequence):
     return "".join([_char_map[x] for x in sequence])

class Mrts(models.Model):
     user=models.ForeignKey(User)
     title=models.CharField(max_length=100)
     picture_1=models.ImageField(upload_to="photos")
     description=HTMLField(null=True,blank=True)
     slug=models.SlugField(max_length=100, unique=True)
     pub_date=models.DateTimeField()

     def __unicode__(self):
         return u'%s' %(self.title)

     def get_short_id(self):
          _id=self.id
           digits=[]
           while _id > 0:
              rem= _id % 62
              digits.append(rem)
              _id /=62
           digits.reverse()
          return index_to_char(digits)

     @staticmethod
     def decode_id(string):
        i=0
        for c in string:
            i=i*64+_char_map.index(c)
        return i

     def save(self, *args, **kwargs):
         if not self.id:
            self.slug=slugify(self.title)
         super(Mrts,self).save(*args,**kwargs)

Views.py

页面网址缩短

  def artdetail(request,mrts_id,slug):
      post=Mrts.objects.get(id=mrts_id,slug=slug)

      currentUrl = request.build_absolute_uri(post.get_short_id())
      return render_to_response('postdetail.html',{'post':post, ' Mrts':Mrts,'currentUrl':currentUrl},context_instance=RequestContext(request))

Urls.py

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

模板

 {{currentUrl}}

如何正确缩短?模型中可以用来缩短网址的任何好方法吗?

1 个答案:

答案 0 :(得分:1)

您需要在urls.py中输入缩短的网址架构:

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

您的模型上获取两种类型网址的方法:

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()])

处理短网址的视图(此网址只是重定向到完整网址):

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)

您可以在这样的模板中显示缩短的网址(其中postMrts个对象):

{{ post.get_short_url }}