[Answered ]-Error: Django model form data not being saved in the database

1👍

You should not construct a new form, since then it will not render the errors. Likely you did not pass request.FILES, and the enctype="…" [mdn-doc] is also missing in the <form> tag:

def postsform(request):
    if request.method == 'POST':
        form = BlogForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('blog')
        else:
            # no new BlogForm
            messages.warning(request, 'Oops! Something went wrong.')
    else:
        form = BlogForm()
    return render(request, 'blog/postform.html', {'form': form})

and in the HTML form:

<form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {{form.as_p}}
    <button type="submit">Publish</button>
</form>

Leave a comment