[Answered ]-Tags are not being stored in the database even after saving form in django

1👍

This is because you use commit=False for the form: then the form has no means to save the many-to-many fields. It is also not necessary to do that, you can work with:

def post(request):
    if request.method == 'POST':
        form = PostModelForm(request.POST)
        if form.is_valid():
            form.instance.user = request.user  # set the user
            post = form.save()  # save the form
            ImagesPostModel.objects.bulk_create([
                ImagesPostModel(post=post, images=image)
                for image in request.FILES.getlist('images')
            ])
        return redirect('/Blog/home/')
    else:
        form = PostModelForm()
    return render(request, 'post.html', {'form': form})

Note: Models normally have no Model suffix. Therefore it might be better to rename PostModel to Post.


Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Leave a comment