Search code examples
djangodjango-formsslugdjango-2.1

Pre-populate slug field into a form field of a Django site


I've create a form for publish a post on a site. Into the model there is a SlugField that is a pre-populated field in admin.py for the title of the post.

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

If I create a post from the administration panel the slug is correctly populated automatically, but the same thing don't happen if I create a post from the form. In this second case the post is created but the slug field remain empty.

I've read that I must use slugify for create a pre-populated field into my form but I have not clear in which method I can do this.

Can I have some example?


Solution

  • Here is the example, in your views.py

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