0

我有一个应用程序,将有一天会允许前端crud,这将创建slug与slugify。但是现在,所有的对象创建工作都在管理区完成,我想知道是否有一种方法可以在管理员内部创建和保存对象时自动生成slu?子?Django自动生成S Admin管理员

这里是前端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 
+0

你试过重写模型的'save'方法? –

回答

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) 
+0

这将打破Django管理员的验证。 –

0

上述解决方案在Django Admin界面中打破验证。我建议:

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 = []