简体   繁体   English

如何在 Django 中创建一个 slug?

[英]How do I create a slug in Django?

I am trying to create a SlugField in Django.我正在尝试在 Django 中创建一个SlugField

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 bbbb .我期待bbbb

You will need to use the slugify function.您将需要使用slugify功能。

>>> 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:您可以通过覆盖save方法自动调用slugify

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 .请注意,当编辑q字段时,上述内容会导致您的 URL 更改,这可能会导致链接断开 It may be preferable to generate the slug only once when you create a new object:创建新对象时,最好只生成一次 slug:

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)

There is corner case with some utf-8 characters有一些 utf-8 字符的角落案例

Example:例子:

>>> from django.template.defaultfilters import slugify
>>> slugify(u"test ąęśćółń")
u'test-aescon' # there is no "l"

This can be solved with Unidecode这可以用Unidecode解决

>>> from unidecode import unidecode
>>> from django.template.defaultfilters import slugify
>>> slugify(unidecode(u"test ąęśćółń"))
u'test-aescoln'

A small correction to Thepeer's answer: To override save() function in model classes, better add arguments to it:对 Thepeer 答案的一个小更正:要覆盖模型类中的save()函数,最好为其添加参数:

from django.utils.text import slugify

def save(self, *args, **kwargs):
    if not self.id:
        self.s = slugify(self.q)

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

Otherwise, test.objects.create(q="blah blah blah") will result in a force_insert error (unexpected argument).否则, test.objects.create(q="blah blah blah")将导致force_insert错误(意外参数)。

If you're using the admin interface to add new items of your model, you can set up a ModelAdmin in your admin.py and utilize prepopulated_fields to automate entering of a slug:如果您使用的管理界面增加模型的新项目,你可以设置ModelAdminadmin.py并利用prepopulated_fields自动进入蛞蝓的:

class ClientAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug': ('name',)}

admin.site.register(Client, ClientAdmin)

Here, when the user enters a value in the admin form for the name field, the slug will be automatically populated with the correct slugified name .在这里,当用户在管理表单中为name字段输入值时, slug将自动填充正确的 slugified name

In most cases the slug should not change, so you really only want to calculate it on first save:在大多数情况下,slug 不应该改变,所以你真的只想在第一次保存时计算它:

class Test(models.Model):
    q = models.CharField(max_length=30)
    s = models.SlugField(editable=False) # hide from admin

    def save(self):
        if not self.id:
            self.s = slugify(self.q)

        super(Test, self).save()

Use prepopulated_fields in your admin class:在您的管理类中使用prepopulated_fields

class ArticleAdmin(admin.ModelAdmin):
    prepopulated_fields = {"slug": ("title",)}

admin.site.register(Article, ArticleAdmin)

If you don't want to set the slugfield to Not be editable, then I believe you'll want to set the Null and Blank properties to False.如果您不想将 slugfield 设置为不可编辑,那么我相信您需要将 Null 和 Blank 属性设置为 False。 Otherwise you'll get an error when trying to save in Admin.否则,尝试在 Admin 中保存时会出现错误。

So a modification to the above example would be::因此,对上述示例的修改将是::

class test(models.Model):
    q = models.CharField(max_length=30)
    s = models.SlugField(null=True, blank=True) # Allow blank submission in admin.

    def save(self):
        if not self.id:
            self.s = slugify(self.q)

        super(test, self).save()

I'm using Django 1.7我正在使用 Django 1.7

Create a SlugField in your model like this:在您的模型中创建一个 SlugField,如下所示:

slug = models.SlugField()

Then in admin.py define prepopulated_fields ;然后在admin.py限定prepopulated_fields ;

class ArticleAdmin(admin.ModelAdmin):
    prepopulated_fields = {"slug": ("title",)}

您可以查看SlugField文档,以更具描述性的方式了解有关它的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM