如何在django表单中自动填充slug字段



我想允许网站用户使用我制作的表单创建博客文章,但slug字段不是从前端自动填充的,而是从后端(管理页面(填充的,这不是我想要的。当用户想要创建帖子时,我希望用标题填充段塞字段,例如这是一个例子请我如何进行

型号.py

class Blog(models.Model):
title = models.CharField(max_length=10000, null=True, blank=True, verbose_name="Title")
slug = models.SlugField(unique=True)
content = RichTextField()
image = models.ImageField(upload_to="blog-images/%Y/%m/%d/", verbose_name="Post Thumbnail")
def get_absolute_url(self):
return reverse("blog:blog-details", args=[self.slug])

def __str__(self):
return self.title

views.py

@login_required
def new_post(request):
info = Announcements.objects.filter(active=True)
categories = Category.objects.all()
if request.method == "POST":
form = BlogPostForm(request.POST, request.FILES)
if form.is_valid():
form.instance.creator = request.user
form.save()  # ← no commit=False
messages.success(request, f'Hi, Your Post have been sent for review and would be live soon!')
return redirect('blog:home')
else:
form = BlogPostForm()
context = {
'form': form,
'info': info,
'categories': categories
}
return render(request, 'blog/newpost.html', context)

forms.py注意如果我从字段中删除"段塞",它会抛出一个错误,说需要段塞

class BlogPostForm(forms.ModelForm):
class Meta:
model = Blog
fields = ('title', 'slug', 'content', 'image', 'category')

newpost.html

<form action="" method="POST" enctype="multipart/form-data">
<p><span style="color: black;"><b>NOTE</b></span>: For slug field, input the title as slug field but with hypens in between text <br> e.g <span style="color: black;"><b> "this-is-a-new-post"</b></span></p>
{% csrf_token %}
{{form|crispy}}
{{form.media}}
<div class="form-group">
<button class="btn theme-bg rounded" type="submit">Post Content</button>
</div>
</form>
Django已经有了一个处理slugs的方法。您可以覆盖保存模型方法并添加slugify字段。
from django.utils.text import slugify
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)

相关内容

  • 没有找到相关文章

最新更新