Home > Software design >  why can't hide slug field in django admin?
why can't hide slug field in django admin?

Time:09-30

when i try to exclude 'slug' field in django admin form,i got this msg: "KeyError at /admin/post/post/add/ "Key 'slug' not found in 'PostForm'. Choices are: author, content, image, title." why? django code: model: 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)

thank you !

CodePudding user response:

You have chosen to exclude it from the admin. But it is required by the database to have a value.

You need to add null=True and blank=True to the field:

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

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

See Django Docs: ModelAdmin options

CodePudding user response:

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

Note:

Don't set null on CharField.blank is enough.

you can add the slug field to readonly_fields in the admin

  • Related