0

When I attach an image, the it returns null in the console but it goes on to post the text data, I want to be able to include the image file too.

NOTE: when I upload image from the Rest api admin side, it works well and image displays, meaning that my Ajax image upload is the one lacking

form.html

<form id='userpost-form' class='form' enctype="multipart/form-data" action="" method="POST"  data-filescount=0> {% csrf_token %} 

    {{ form| crispy }}

    <button type="submit" class="btn btn-success btn-sm float-right" id="post_frame">{{ submit_btn }}</button>
</form>

Ajax Improved

$("#userpost-form").submit(function(e) {
  e.preventDefault();
  var this_ = $(this)
  // var formData = this_.serialize()
  // console.log("working...")
  // console.log(this_.serialize())
  var formData = new FormData(this_.serialize());
  formData.append('image', this_.get(0));
  console.log(formData);
  $.ajax({
    url: "/api/posts/create/",
    data: formData,
    method: "POST",
    dataType: "json",
    success: function(data) {
      // console.log(data)
      this_.find("input[type=text], textarea").val("")
      // this_.find("input[type=file]").val("")
      // $('#uploadfrm')[0].reset(); // Reset form data
      attachPosts(data, true)
    },

    error: function(data) {
      console.log("error")
    },
  })

}) //post form end brac

views.py

class PostUserCreateAPIView(generics.CreateAPIView):
    queryset = Post.objects.all()
    serializer_class = PostDetailSerializer
    permission_classes = [permissions.IsAuthenticated]
    parser_classes = (MultiPartParser, FormParser,)

    def perform_create(self, serializer):
        serializer.save(content_object=self.request.user, image=self.request.data.get('image'))

serailizers.py

class PostDetailSerializer(serializers.ModelSerializer):

    class Meta:
        model = Post
        fields = ["id", "user", "content", "image", "date_display",
        # "timesince",
    ]

This Code posts the data very well without the image, So my challenge is on how to include the image file

Aneesh R S
  • 3,807
  • 4
  • 23
  • 35
dungu
  • 125
  • 1
  • 13

1 Answers1

0

I quote from the django docs:

When Django handles a file upload, the file data ends up placed in request.FILES

Instead of using self.request.data.get('image'), use self.request.FILES.get('image')

anilkumarggk
  • 166
  • 1
  • 11