为什么不能在 django 管理中隐藏 slug 字段?

why can't hide slug field in django admin?

当我尝试排除 Django 管理表单中的 'slug' 字段时,我收到了这条消息:“/admin/post/post/add/ 处的 KeyError “在 'PostForm' 中未找到密钥 'slug'。选项包括:作者、内容、图像、标题。” 为什么? 姜戈代码: 型号:models.py

from django.db import models
from django.utils import timezone
from django.urls import reverse

# Create your models here.
class Post(models.Model):
    title= models.CharField(max_length=50,null=False,blank=False)
    content= models.TextField(max_length=2000,null=False,blank=False)
    image= models.ImageField( upload_to="post-img/")
    created_at=models.DateTimeField(default=timezone.now)
    author=models.CharField(max_length=50,null=True,blank=True)
    slug=models.SlugField(max_length=30)
    

    

    class Meta:
        verbose_name =("Post")
        verbose_name_plural =("Posts")

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("PostDetail", kwargs={'slug': self.slug})

    def headline(self):
        return self.content[:50]+'...'

admin.py :

from django.contrib import admin
from .models import Post

# Register your models here.


class PostAdmin(admin.ModelAdmin):
    exclude=('created_at','slug',)
    # fieldsets=(({'fields':('title','content','image',)}),)
    
    list_display=['title','headline','author','created_at']
    prepopulated_fields = {'slug': ('title',)}

    
admin.site.register(Post,PostAdmin)

谢谢!

您已选择将其从管理员中排除。但是要求数据库有值。

您需要在字段中添加 null=Trueblank=True

slug=models.SlugField(max_length=30, blank=True,  null=True)

Note: Ensure you makemigrations and migrate for this to take effect

Django Docs: ModelAdmin options

slug=models.SlugField(max_length=30, blank=True, editable=False)

注:

不要在 CharField 上设置 nullblank 就足够了。

您可以在管理

中将slug field添加到readonly_fields