How to send images as a binary data with the request

Here's what I have

models.py

class Post(models.Model):
    id = models.AutoField(primary_key=True)
    text = models.TextField(max_length=165)
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f'{self.author} posts "{self.text}"'


class Images(models.Model):
    id = models.AutoField(primary_key=True)
    image = models.ImageField(upload_to='images/')
    post_id = models.ForeignKey(Post, on_delete=models.CASCADE)

    def __str__(self):
        return f'{self.post_id.id} - "{self.image}"'

serializers.py

class ImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Images
        fields = ('image',)

class PostSerializer(serializers.ModelSerializer):
    images = ImageSerializer(many=True, read_only=True, source='images_set')
    author = UserSerializer(read_only=True)
    comments = CommentSerializer(many=True, read_only=True, source='comment_set')
    likes_count = serializers.SerializerMethodField()


    class Meta:
        model = Post
        fields = ['id', 'author', 'text', 'images', 'created_at', "likes_count", 'comments']

    def create(self, validated_data):
        validated_data["author"] = self.context["request"].user
        return super().create(validated_data)

    def validate(self, data):
        if data.get('author') == self.context["request"].user:
            raise serializers.ValidationError('Logged in User is not an Author')
        return data

    def get_likes_count(self, obj):
        return obj.postlikes_set.count()

views.py

class NewPost(APIView):
    permission_classes = [IsAuthenticated]
    parser_classes = [JSONParser]

    def post(self, request):
        text = request.data.get("text")
        post_id = Post.objects.create(author_id=request.user.id ,text=text)
        images = request.FILES.getlist('images')
        for image in images:
            Images.objects.create(image=image, post_id=post_id)
        return Response({"message": "Успешно", 'received data': request.data}, status=status.HTTP_201_CREATED)

I need to send post data consisting of text and multiple images. I've been told the way to do it is to send images "as binary data" and was linked docs pages for JSON Parsers. I have no idea what that actually means. If I try to send them like so:

POST {{baseUrl}}/newpost/
Content-Type: application/json
Authorization: Token 195c9587649b81fb9a19eeb19024f63d98790f27

{
  "text": "a new post",
  "images": ["small_django_logo.png", "small_django_logo.png"]
}

The images won't come through. I'm sending stuff by sending request via Visual Studio.

When I send the GET reqeust, I get this:

{
    "id": 33,
    "author": {
      "id": 1,
      "username": "admin"
    },
    "text": "a new post",
    "images": [],
    "created_at": "2025-02-04T14:14:24.032092Z",
    "likes_count": 0,
    "comments": []
}

Images are tricky to send from frontend to django rest framework, but once you do, the process can always be improved, and used in multiple places.

try this -

const formData = new FormData();
formData.append("profileImage", states.profilePic);
formData.append("name", "any_string_value");

axios({
  url: `http://localhost:8000/employee/empMaster/${empId}/`,
  method: "PUT",
  data: formData,
  headers: {
    Authorization: `Token ${token}`,
  },
})
  .then((d) => {})
  .catch((err)=>{})

Side Note - try learning about base64 and getBase64 so that you can read the image and can click to view it. This is used to convert image file type to viewable image.

For your answer, read more about FormData

thanks

Вернуться на верх