我想获取一个特定的页面 url 并自动缩短 url,并将其显示给用户。编写以下代码后,它没有正确缩短。
页面网址
127.0.0.1:8000/artlyf/1/topman
缩短后的页面网址
127.0.0.1:8000/artlyf/1/topman/b
模型.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)
视图.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))
网址.py
url(r'^artlyf/(?P<mrts_id>\d+)/(?P<slug>[-\d\w]+)/$', 'artapp.views.artdetail', name='artdetail'),
模板
{{currentUrl}}
如何正确缩短?模型中有什么好方法可以用来缩短网址吗?