将子弹字段预填充到Django站点的表单字段中

时间:2019-03-23 13:34:26

标签: django django-forms slug django-2.1

我已经创建了一个表单,用于在网站上发布帖子。在模型中,有一个SlugField,它是admin.py中帖子标题的预填充字段。

forms.py

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",
....
                ]

如果我是从管理面板创建帖子的,则将自动正确填充该条目,但如果从表单创建帖子,则不会发生相同的情况。在第二种情况下,创建了帖子,但是子弹字段保持为空。

我读到我必须使用slugify在表单中创建一个预填充字段,但是我不清楚我可以用哪种方法进行操作。

我能举个例子吗?

3 个答案:

答案 0 :(得分:1)

以下是您的views.py

中的示例
form = PostForm(request.POST):
   if form.is_valid():
     post = form.save(commit=False)
     post.slug = slugify(post.title)
     post.save()
    ...

答案 1 :(得分:0)

对coderasha指示有一些精确的说明:从表单中删除子弹字段很重要

就我而言:

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",
....
                ]

答案 2 :(得分:0)

class Post(models.Model):
    title = models.CharField(max_length=150)
    image = models.ImageField(upload_to='images/', blank=True)
    date_created = models.DateTimeField(auto_now_add=True)
    slug = models.SlugField(unique=True)

def pre_save_slugify_receiver(sender, instance, *args, **kwargs):
    slug = slugify(instance.title)
    instance.slug = slug

pre_save.connect(pre_save_slugify_receiver, sender=Post)