我创建了一个用于在网站上发布帖子的表单。在模型中有一个SlugField,它是admin.py中预先填充的字段,用于帖子的标题。
forms.朋友
class TestPostModelForm(forms.ModelForm):
title = forms.CharField(
max_length=70,
label="Titolo",
help_text="Write post title here. The title must be have max 70 characters",
widget=forms.TextInput(attrs={"class": "form-control form-control-lg"}),
)
slug_post = forms.SlugField(
max_length=70,
label="Slug",
help_text="Slug is a field in autocomplete mode, but if you want you can modify its contents",
widget=forms.TextInput(attrs={"class": "form-control form-control-sm"}),
)
.....
class Meta:
model = TestPostModel
fields = [
"title",
"slug_post",
"description",
"contents",
....
]
如果我从管理面板创建一个帖子,则会自动正确填充slug,但如果我从表单创建一个帖子,则不会发生相同的事情。在第二种情况下,创建了帖子但是slug字段保持为空。
我已经读过我必须使用slugify在我的表单中创建一个预先填充的字段,但我还不知道我可以用哪种方法做到这一点。
我可以举个例子吗?
以下是views.py中的示例
form = PostForm(request.POST):
if form.is_valid():
post = form.save(commit=False)
post.slug = slugify(post.title)
post.save()
...
在coderasha指示上稍微精确一点:从表单中删除slug字段很重要。
就我而言:
class TestPostModelForm(forms.ModelForm):
title = forms.CharField(
max_length=70,
label="Titolo",
help_text="Write post title here. The title must be have max 70 characters",
widget=forms.TextInput(attrs={"class": "form-control form-control-lg"}),
)
.....
class Meta:
model = TestPostModel
fields = [
"title",
"description",
"contents",
....
]