如何 auto-populate 在 Django 表单中插入字段
how to auto-populate slug field in django forms
我想允许网站的用户从我制作的表单创建博客 post,但是 slug 字段不会从前端自动填充,而是从后端(管理页面)获取人口稠密,这不是我想要的。当用户想要创建 post 例如 this-is-an-example 时,我希望 slug 字段填充标题
]
models.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 注意 如果我从字段中删除 'slug',它会抛出一个错误,提示需要 slug
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 已经有一个处理 slug 的方法。您可以覆盖您的保存模型方法并添加 slugify 字段。
from django.utils.text import slugify
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
我想允许网站的用户从我制作的表单创建博客 post,但是 slug 字段不会从前端自动填充,而是从后端(管理页面)获取人口稠密,这不是我想要的。当用户想要创建 post 例如 this-is-an-example 时,我希望 slug 字段填充标题
]models.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 注意 如果我从字段中删除 'slug',它会抛出一个错误,提示需要 slug
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 已经有一个处理 slug 的方法。您可以覆盖您的保存模型方法并添加 slugify 字段。
from django.utils.text import slugify
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)