[Answered ]-Django rest framework, AttributeError: 'str' object has no attribute 'data' and unable to upload image using forms

1👍

For the form, you need to add enctype information to bind the file to the form, like this:

<form method="post" enctype="multipart/form-data">
{% csrf_token %}
        {% render_form serializer %}

    <input type="submit" value="Wyślij">
</form>

For the actual problem regarding str object has no attribute data, DRF documentation mentions that:

Django rest framework looks for render_form template tag, to render Serializer.

The error is happening because in the html file it is looking for rendering the serializer using render_form tag. Since you are passing the serializer as serializer context variable, you need to send the serializer in post method like this:

   if serializer.is_valid():
        serializer.save(uploaded_by=self.request.user)
        return Response({"serializer":serializer})

If you do not want to render the form again, I suggest either redirect it to a different url where you get the same response in JSON format using JSONRenderer. If you intend to render in the response in HTML, then I would put another context variable, like this:

# view
if serializer.is_valid():
    serializer.save(uploaded_by=self.request.user)
    return Response({"serializer":serializer, "data": serializer.data})

# template
{% if data %}
    {{ data }}
{{ endif }}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
        {% render_form serializer %}

    <input type="submit" value="Wyślij">
</form>
👤ruddra

Leave a comment