如何在Django中创建蛞蝓?

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


I am trying to create a SlugField in Django.

我试图在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

我很期待b-b-b-b

8 个解决方案

#1


358  

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:

您可以通过覆盖保存方法自动调用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. It may be preferable to generate the slug only once when you create a new object:

请注意,当编辑q字段时,上面的内容将导致您的URL发生更改,这可能导致断开链接。在创建新对象时,最好只生成一次蛞蝓:

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)

#2


105  

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'

#3


57  

A small correction to Thepeer's answer: To override save() function in model classes, better add arguments to it:

对同行的回答做一个小小的修正:在模型类中重写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 blah")会导致force_insert error(意想不到的参数)。

#4


28  

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:

如果您正在使用管理界面添加您的模型的新项目,您可以在您的管理中设置一个ModelAdmin。使用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.

在这里,当用户在admin表单中输入name字段的值时,段塞将自动填充正确的段塞名。

#5


22  

In most cases the slug should not change, so you really only want to calculate it on first save:

在大多数情况下,段塞不应该改变,所以你只需要在第一次保存时计算它:

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

#6


5  

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. Otherwise you'll get an error when trying to save in Admin.

如果不希望将slufield设置为不可编辑,那么我认为您应该将Null和Blank属性设置为False。否则,在尝试在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()

#7


4  

Use prepopulated_fields in your admin class:

在管理类中使用prepopulated_fields:

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

admin.site.register(Article, ArticleAdmin)

http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.prepopulated_fields

http://docs.djangoproject.com/en/dev/ref/contrib/admin/ django.contrib.admin.ModelAdmin.prepopulated_fields

#8


2  

I'm using Django 1.7

我使用Django 1.7

Create a SlugField in your model like this:

在你的模型中创建一个斯莱格菲尔德,如下所示:

slug = models.SlugField()

Then in admin.py define prepopulated_fields;

在管理。py定义prepopulated_fields;

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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2009/05/08/1cd978ae1503bb27754279ee6e4231e0.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号