自动填充子弹字段在Django中不起作用

时间:2019-02-19 04:34:55

标签: django django-rest-framework

我正在尝试发布使用slug作为发布网址的帖子。我添加了子弹字段,但它不会自动填充。我想使其自动填充。 到目前为止,我已经做到了。我在末尾添加了pre_save。

我试图保存来自django管理员的帖子,它说像这样

  

此字段为必填项。

     

posts / models.py

from django.db import models
from django.core.validators import FileExtensionValidator
from django.db.models.signals import pre_save
from django.utils.text import slugify
# Create your models here.



class Category(models.Model):
    title = models.CharField(max_length = 120, verbose_name="Title" )
    updated_at = models.DateTimeField(auto_now_add=True, verbose_name="Updated at")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at")
    class Meta:
        verbose_name = "Category"
        verbose_name_plural = "Categories"
        ordering = ['title']
    def __str__(self):
        return self.title



class Posts(models.Model):
    title = models.CharField(max_length=60)
    slug = models.SlugField(unique = True)
    file_upload = models.FileField(null= True, blank=True, validators=[FileExtensionValidator(['pdf'])])
    content = models.TextField()
    category = models.ForeignKey(Category, null= True,verbose_name="Category", on_delete=models.CASCADE)
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

    # class Meta:
    #     verbose_name = "Post"
    #     verbose_name_plural = "Posts"
    #     ordering = ['-created_at']


    def __unicode__(self):
        return self.title 

    def __str__(self):
        return self.title

def create_slug(instance, new_slug=None):
    slug = slugify(instance.title, allow_unicode = True)
    if new_slug is not None:
        slug = new_slug
    qs = Posts.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

def pre_save_post_receiver( instance, sender,*args, **kwargs):
    if not instance.slug:
        instance.slug = create_slug(instance)
pre_save.connect(pre_save_post_receiver, sender=Posts)

2 个答案:

答案 0 :(得分:0)

从您的代码instance.title开始,对于生成块值始终很重要。然后,不触发pre_save信号的一种可能方法是覆盖模型保存函数并在那里分配值。

def create_slug(title, new_slug=None):
    slug = slugify(title, allow_unicode = True)
    if new_slug is not None:
        slug = new_slug
    qs = Posts.objects.filter(slug=slug).order_by("-id")
    exists = qs.exists()
    if exists:
        new_slug = "%s-%s"%(slug, qs.first().id)
        return create_slug(title, new_slug=new_slug)
    return slug



class Posts(models.Model):
    title = models.CharField(max_length=60)
    slug = models.SlugField(unique = True)
    file_upload = models.FileField(null= True, blank=True, validators=[FileExtensionValidator(['pdf'])])
    content = models.TextField()
    category = models.ForeignKey(Category, null= True,verbose_name="Category", on_delete=models.CASCADE)
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

    # class Meta:
    #     verbose_name = "Post"
    #     verbose_name_plural = "Posts"
    #     ordering = ['-created_at']

    def save(self, *args, **kwargs):
        if not self.slug:
               self.slug = create_slug(self.title)
        return super(Posts, self).save(*args, **kwargs)  # important to call this

    def __unicode__(self):
        return self.title 

    def __str__(self):
        return self.title

我真的希望这个解决方案能够奏效。使用字段默认可调用函数link的另一种可能方式,但是从您的代码中我可以看到title也很重要。我不确定,但是接下来的事情也可以工作。

def create_slug(title, new_slug=None):
        slug = slugify(title, allow_unicode = True)
        if new_slug is not None:
            slug = new_slug
        qs = Posts.objects.filter(slug=slug).order_by("-id")
        exists = qs.exists()
        if exists:
            new_slug = "%s-%s"%(slug, qs.first().id)
            return create_slug(title, new_slug=new_slug)
        return slug



class Posts(models.Model):
    title = models.CharField(max_length=60)
    slug = models.SlugField(unique = True, default=create_slug(self.title))
    file_upload = models.FileField(null= True, blank=True, validators=[FileExtensionValidator(['pdf'])])
    content = models.TextField()
    category = models.ForeignKey(Category, null= True,verbose_name="Category", on_delete=models.CASCADE)
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

    # class Meta:
    #     verbose_name = "Post"
    #     verbose_name_plural = "Posts"
    #     ordering = ['-created_at']



    def __unicode__(self):
        return self.title 

    def __str__(self):
        return self.title

答案 1 :(得分:0)

您可以使用django-slugger

然后将其添加到管理员中添加

  

admin.py

import React, { useRef } from 'react'
import styled from 'styled-components'

export function Modal({ show, showModalSet, children }) {
  const modalRef = useRef(null)

  function handleClick(e) {
    if (e.target == modalRef.current) showModalSet(false)
  }

  return (
    <DivModal onClick={handleClick} show={show} ref={modalRef}>
      {children}
    </DivModal>
  )
}

const DivModal = styled.div`
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.8);
  display: ${({ show }) => (show ? 'block' : 'none')};
  z-index: 10;
  overflow-y: scroll;
`