0

我想获取一个特定的页面 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}}

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

4

1 回答 1

1

对于缩短的 url 架构,您需要在 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')

以及模型上用于获取两种类型 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()])

处理短 url 的视图(这个只是重定向到完整的 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)

您可以在这样的模板中显示缩短的 URL(对象在哪里postMrts

{{ post.get_short_url }}
于 2013-10-14T07:29:04.813 回答