python 有没有一种简单的方法可以从 CharField 填充 SlugField?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/141487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 19:33:00  来源:igfitidea点击:

Is there an easy way to populate SlugField from CharField?

pythondjangoslug

提问by ashchristopher

class Foo(models.Model):
    title = models.CharField(max_length=20)
    slug = models.SlugField()

Is there a built-in way to get the slug field to autopopulate based on the title? Perhaps in the Admin and outside of the Admin.

是否有内置方法可以根据标题自动填充 slug 字段?也许在管理员和管理员之外。

回答by camflan

for Admin in Django 1.0 and up, you'd need to use

对于 Django 1.0 及更高版本中的 Admin,您需要使用

prepopulated_fields = {'slug': ('title',), }

in your admin.py

在你的 admin.py

Your key in the prepopulated_fields dictionary is the field you want filled, and the value is a tuple of fields you want concatenated.

prepopulated_fields 字典中的键是要填充的字段,值是要连接的字段的元组。

Outside of admin, you can use the slugifyfunction in your views. In templates, you can use the |slugifyfilter.

在管理员之外,您可以slugify在视图中使用该功能。在模板中,您可以使用|slugify过滤器。

There is also this package which will take care of this automatically: https://pypi.python.org/pypi/django-autoslug

还有这个包会自动处理这个:https: //pypi.python.org/pypi/django-autoslug

回答by AdamKG

Outside the admin, see this django snippet. Put it in your .save(), and it'll work with objects created programmatically. Inside the admin, as the others have said, use prepopulated_fields.

在管理员之外,请参阅此 django 片段。将它放在您的 中.save(),它将与以编程方式创建的对象一起使用。在管理员内部,正如其他人所说,使用prepopulated_fields.

回答by Nick Sergeant

For pre-1.0:

对于 1.0 之前的版本:

slug = models.SlugField(prepopulate_from=('title',))

should work just fine

应该工作得很好

For 1.0, use camflan's

对于 1.0,使用camflan 的

回答by carefulweb

You can also use pre_save django signal to populate slug outside of django admin code. See Django signals documentation.

您还可以使用 pre_save django 信号在 django 管理代码之外填充 slug。请参阅Django 信号文档

Ajax slug uniqueness validation will be useful too, see As-You-Type Slug Uniqueness Validation @ Irrational Exuberance

Ajax slug 唯一性验证也很有用,请参阅As-You-Type Slug Uniqueness Validation @ Irrational Exuberance

回答by Andreas Bergstr?m

Thought I would add a complete and up-to-date answer with gotchas mentioned:

以为我会添加一个完整且最新的答案,其中提到了一些陷阱:

1. Auto-populate forms in Django Admin

1. 在 Django Admin 中自动填充表单

If you are only concerned about adding and updating data in the admin, you could simply use the prepopulated_fieldsattribute

如果您只关心在管理员中添加和更新数据,您可以简单地使用prepopulated_fields属性

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

admin.site.register(Article, ArticleAdmin)

2. Auto-populate custom forms in templates

2. 在模板中自动填充自定义表单

If you have built your own server-rendered interface with forms, you could auto-populate the fields by using either the |slugifytamplate filter or the slugifyutility when saving the form (is_valid).

如果您使用表单构建了自己的服务器呈现界面,则可以在保存表单 (is_valid) 时使用|slugify模板过滤器或slugify实用程序自动填充字段。

3. Auto-populating slugfields at model-level with django-autoslug

3. 使用 django-autoslug 在模型级别自动填充 slugfields

The above solutions will only auto-populate the slugfield (or any field) when data is manipulated through those interfaces (the admin or a custom form). If you have an API, management commands or anything else that also manipulates the data you need to drop down to model-level.

当通过这些接口(管理员或自定义表单)操作数据时,上述解决方案只会自动填充 slugfield(或任何字段)。如果您有 API、管理命令或其他任何也可以操作数据的东西,那么您需要下拉到模型级别。

django-autoslugprovides the AutoSlugField-fields which extends SlugField and allows you to set which field it should slugify neatly:

django-autoslug提供了 AutoSlugField-fields,它扩展了 SlugField 并允许您设置它应该整齐地插入哪个字段:

class Article(Model):
    title = CharField(max_length=200)
    slug = AutoSlugField(populate_from='title')

The field uses pre_save and post_save signals to achieve its functionality so please see the gotcha text at the bottom of this answer.

该字段使用 pre_save 和 post_save 信号来实现其功能,因此请参阅此答案底部的陷阱文本。

4. Auto-populating slugfields at model-level by overriding save()

4. 通过覆盖 save() 在模型级别自动填充 slugfields

The last option is to implement this yourself, which involves overriding the default save() method:

最后一个选项是自己实现,这涉及覆盖默认的 save() 方法:

    class Article(Model):
        title = CharField(max_length=200)
        slug = SlugField()

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(Job, self).save(*args, **kwargs)

NOTE: Bulk-updates will bypass your code (including signals)

注意:批量更新将绕过您的代码(包括信号)

This is a common miss-understanding by beginners to Django. First you should know that the pre_save and post_save signals are directly related to the save()-method. Secondly the different ways to do bulk-updates in Django all circumvent the save()-method to achieve high performance, by operating directly on the SQL-layer. This means that for the example model used in solution 3 or 4 above:

这是 Django 初学者常见的误解。首先,您应该知道 pre_save 和 post_save 信号与 save() 方法直接相关。其次,在 Django 中进行批量更新的不同方法都绕过了 save() 方法,通过直接在 SQL 层上操作来实现高性能。这意味着对于上述解决方案 3 或 4 中使用的示例模型:

  • Article.objects.all().update(title='New post') will NOTupdate the slug of any article
  • Using bulk_createor bulk_updateon the Article model will NOTupdate the slug of any article.
  • Since the save()-method is not called, no pre_save or post_save signals will be emitted.
  • Article.objects.all().update(title='New post')不会更新任何文章的 slug
  • 在文章模型上使用bulk_createbulk_update不会更新任何文章的 slug。
  • 由于未调用 save() 方法,因此不会发出 pre_save 或 post_save 信号

To do bulk updates and still utilize code-level constraints the only solution is to iterate objects one by one and call its save()-method, which has drastically less performance than SQL-level bulk operations. You could of course use triggers in your database, though that is a totally different topic.

要进行批量更新并仍然利用代码级约束,唯一的解决方案是一个一个地迭代对象并调用其 save() 方法,该方法的性能远低于 SQL 级批量操作。您当然可以在数据库中使用触发器,尽管这是一个完全不同的主题。

回答by Jon Lemmon

autoslughas worked quite well for me in the past. Although I've never tried using it with the admin app.

autoslug过去对我来说效果很好。虽然我从未尝试过将它与管理应用程序一起使用。