【问题标题】:Auto Generated Slugs in Django Admin在 Django Admin 中自动生成的 Slug
【发布时间】:2017-07-13 01:51:21
【问题描述】:

我有一个应用程序有一天会允许前端 crud,它将创建带有 slugify 的 slug。不过现在,所有对象创建都在管理区域完成,我想知道是否有一种方法可以在从管理中创建和保存对象时自动生成 slug?

这里是前端slugify的方法;不确定它是否相关。谢谢。

def create_slug(instance, new_slug=None):
    slug = slugify(instance.title)
    if new_slug is not None:
        slug = new_slug
    qs = Veteran.objects.filter(slug=slug).order_by('-id')
    exists = qs.exists()
    if exists:
        new_slug = '%s-%s' % (slug, qs.first().id)
        return create_slug(instance, new_slug=new_slug)
    return slug

【问题讨论】:

标签: django django-models django-templates django-views django-admin


【解决方案1】:

刚刚在另一个答案中使用了这个,我的剪贴板中有完全正确的代码。我为我的一个模型做这个:

from django.utils.text import slugify
class Event(models.Model):

    date = models.DateField()
    location_title = models.TextField()
    location_code = models.TextField(blank=True, null=True)
    picture_url = models.URLField(blank=True, null=True, max_length=250)
    event_url = models.SlugField(unique=True, max_length=250)

    def __str__(self):
        return self.event_url + " " + str(self.date)

    def save(self, *args, **kwargs):
        self.event_url = slugify(self.location_title+str(self.date))
        super(Event, self).save(*args, **kwargs)

【讨论】:

  • 这将破坏 Django 管理员中的验证。
  • 在 Django 管理员中将 event_url 设置为 read_only_field 然后它就可以工作了
【解决方案2】:

以上解决方案破坏了 Django 管理界面中的验证。我建议:

from django import forms
from django.http.request import QueryDict
from django.utils.text import slugify

from .models import Article


class ArticleForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(ArticleForm, self).__init__(*args, **kwargs)

        # Ensure that data is a regular Python dictionary so we can
        # modify it later.
        if isinstance(self.data, QueryDict):
            self.data = self.data.copy()

        # We assume here that the slug is only generated once, when
        # saving the object. Since they are used in URLs they should
        # not change when valid.
        if not self.instance.pk and self.data.get('title'):
            self.data['slug'] = slugify(self.data['title'])

    class Meta:
        model = Article
        exclude = []

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-26
    • 2021-01-23
    • 1970-01-01
    • 2018-10-30
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    • 2017-12-28
    相关资源
    最近更新 更多