update_view - tags field update gives other values (django-taggit)

Viewed 102

I am trying to build a Blog and for my tag system I thought would be great to use django-taggit but there is a problem when I want to update the BlogPost

This is how I add them when I create the Blog Post:

tag1, tag2 ,tag3

And this is how it looks like when I try to update the Blog Post:

[<Tag: tag1>, <Tag: tag2>, <Tag: tag3>]

blog/forms.py

from django import forms
from .models import BlogPost, Category

class BlogPostForm(forms.Form):
    title = forms.CharField()
    # slug = forms.SlugField()
    content = forms.CharField(widget=forms.Textarea)



# class BlogPostModelForm(forms.ModelForm):
choices = Category.objects.all().values_list('name', 'name')
choice_list = []
for item in choices:
    choice_list.append(item)


class BlogPostForm(forms.ModelForm):
    class Meta:
        model = BlogPost
        fields = ['title', 'category', 'content', 'publish_date', 'image', 'private', 'tags']

        widgets ={
        
            'title': forms.TextInput(attrs={'class': 'form-control'}),
            'category': forms.Select(choices=choice_list, attrs={'class': 'form-control'}),
            # 'slug': forms.TextInput(attrs={'class': 'form-control'}),
            'content': forms.Textarea(attrs={'class': 'form-control'}),
            'publish_date': forms.TextInput(attrs={'class': 'form-control'}),
            'image': forms.FileInput(attrs={'class': 'form-control-file'}),
            'private': forms.CheckboxInput(attrs={'class': 'form-check-label'}),
            'tags': forms.TextInput(attrs={'class': 'form-control'}),
        }

blog/views.py

  • update_view
@login_required(login_url='login')
def blog_post_update_view(request, slug):
    obj = get_object_or_404(BlogPost, slug=slug)
    form = BlogPostForm(request.POST or None, instance=obj)
    if form.is_valid():
        form.save(commit=False)
        form.save_m2m()
        return redirect('/blog')
    template_name = 'form.html'
    context = {"title": f"Update {obj.title}", "form": form}

    return render(request, template_name, context)  

Can anyone explain how can I fix this?

0 Answers
Related