我尝试为我的 django 网站添加帖子博客文章页面。但是将其添加到添加帖子页面后,它的 slug 模型不会自动生成,但它在管理页面中运行良好。
标题字段中的示例,当我输入如何快速掌握 python 时,它只会在管理页面中使用“-”在 slug 字段中自动生成。但是当我在添加帖子页面上输入相同的内容时,它不会自动生成 slug 。
我的代码
模型.py
from django.db import models
from django.contrib.auth.models import User
from django_summernote.fields import SummernoteTextField
from django.urls import reverse
from django.template.defaultfilters import slugify
STATUS = (
(0,"Draft"),
(1,"Publish")
)
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
title_type = models.CharField(max_length=50, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts')
updated_on = models.DateTimeField(auto_now= True)
content = SummernoteTextField(blank=True, null=True)
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
image = models.ImageField(upload_to='images',null=True, blank=True)
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('home')
views.py
class AddPostView(CreateView):
model = Post
form_class = PostForm
template_name = 'add_post.html'
slug 字段不应可编辑,请从 AddPostView 和 Admin 的字段中删除“slug”字段。
class AddPostView(CreateView):
model = Post
fields = ['title', 'title_type', 'author', 'updated_on', 'content',
'created_on', 'status', 'image']
form_class = PostForm
template_name = 'add_post.html'
对于 admin.py 中的 Model 类,必须在类末尾插入以下行:
prepopulated_fields = {'slug':('<field_to_slug>',)}
这样,您可以在管理视图中保留 slug 字段(无需从 admin.py 中删除)