本文介绍了如何在Django中创建一个slug?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Django中创建一个SlugField。



我创建了这个简单的模型:

  from django.db import models 

class Test(models.Model):
q = models.CharField(max_length = 30)
s = models。 SlugField()

然后我这样做:

 >>>来自mysite.books.models import Test 
>>> t = Test(q =aa a a a,s =b b b b)
>>> t.s
'b b b b'
>>>> t.save()
>>> t.s
'b b b b'
>>>>

我期待bbbb

解决方案

您将需要使用slugify功能。

 >>>来自django.template.defaultfilters import slugify 
>>> slugify(b b b b)
u'b-b-b-b'
>>>

您可以自动调用 slugify 保存方法:

 类测试(models.Model):
q = models.CharField(max_length = 30)
s = models.SlugField()

def save(self,* args,** kwargs):
self.s = slugify(self.q)
super(test,self).save(* args,** kwargs)

请注意,当编辑 q 字段时,上述将导致您的URL更改,其中。创建新对象时,最好只生成一次块:

  class test(models.Model):
q = models.CharField(max_length = 30)
s = models.SlugField()

def save(self,* args,** kwargs):
如果不是自己.id:
#新建的对象,所以设置slug
self.s = slugify(self.q)

super(test,self).save(* args,* * kwargs)


I am trying to create a SlugField in Django.

I created this simple model:

from django.db import models

class Test(models.Model):
    q = models.CharField(max_length=30)
    s = models.SlugField()

I then do this:

>>> from mysite.books.models import Test
>>> t=Test(q="aa a a a", s="b b b b")
>>> t.s
'b b b b'
>>> t.save()
>>> t.s
'b b b b'
>>>

I was expecting b-b-b-b

解决方案

You will need to use the slugify function.

>>> from django.template.defaultfilters import slugify
>>> slugify("b b b b")
u'b-b-b-b'
>>>

You can call slugify automatically by overriding the save method:

class test(models.Model):
    q = models.CharField(max_length=30)
    s = models.SlugField()

    def save(self, *args, **kwargs):
        self.s = slugify(self.q)
        super(test, self).save(*args, **kwargs)

Be aware that the above will cause your URL to change when the q field is edited, which can cause broken links. It may be preferable to generate the slug only once when you create a new object:

class test(models.Model):
    q = models.CharField(max_length=30)
    s = models.SlugField()

    def save(self, *args, **kwargs):
        if not self.id:
            # Newly created object, so set slug
            self.s = slugify(self.q)

        super(test, self).save(*args, **kwargs)

这篇关于如何在Django中创建一个slug?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 04:55