Updating a form with image field using htmx and django

I have a model Post

class Post(models.Model):
    content = models.TextField()
    image = models.ImageField(upload_to='posts',blank=True)

and I have form for that model

class PostModelForm(forms.ModelForm):

    class Meta:
        model = Post
        fields = '__all__'

I'm using htmx and I have some partial templates inside my main template. this is my partial template form to update my post

{% load i18n  crispy_forms_tags widget_tweaks  %}

<form action="" class="mt-2 ml-2" hx-put="{% url 'posts:edit-post-form' post.id %}"
 hx-target="#PostContent-{{post.id}}" enctype="multipart/form-data">
 {% csrf_token %}
 {% render_field form.content class="form-control" name="content" %}
 {% render_field form.image class="form-control" name="image" %}
 <button type='submit' class="btn btn-outline-info">{% trans "Update" %}</button>
</form>

and below you can check my view

from django.http.multipartparser import MultiPartParser
from django.http import QueryDict

def edit_post_form(request,pk):
    try:
        post = Post.objects.get(pk=pk)
        form = PostModelForm(request.POST or None, request.FILES or None ,instance=post)
        if request.user.profile == post.author:
            if request.method == "PUT":
                data = QueryDict(request.body).dict()
                # print(request.META['CONTENT_TYPE'])
                # MultiPartParser(request.META, request, request.upload_handlers).parse()
            
                if form.is_valid():
                    form.save()
                    return redirect("posts:edit-post-detail" ,  pk=post.id)
                else:
                    print(form.errors)
                
                
            return render(request, 'posts/partials/edit_post_form.html',context = 
            {'post':post,'form':form})
        else:
            return redirect("posts:main-post-view")
except ObjectDoesNotExist:
    return HttpResponse("This post has been deleted")

Since I have a "multipart/form-data" when I print data

data = QueryDict(request.body).dict()
print(data)

I'll see the output sth like the dictionary below

{'------WebKitFormBoundary4ZEQZO2qHFj9tp7w\r\nContent-Disposition: form-data; name': '"csrfmiddlewaretoken"\r\n\r\nQu0zvB12321jnzcxdfdasd7ItP9x2tLqnLjjhudnhcARv4zMkqdmzksQFuk56uq\r\n------WebKitFormBoundary4ZEQZO2qHFj9tp7w\r\nContent-Disposition: form-data; name="content"\r\n\r\nnew\r\n------WebKitFormBoundary4ZEQZO2qHFj9tp7w--\r\n'}

I tried to use MultiPartParser but I get an error

django.http.multipartparser.MultiPartParserError: Invalid Content-Type: application/x-www-form-urlencoded

I understood that I need to change the Content-type. but I'm not sure exactly if I'm doing things right or not. would you please give me some advice on this function-based view and how to make it works?

thank you in advance for your help

Back to Top