0

I want to insert image to database.

I use Django Rest Framework and Django BinaryField in model and use Postgresql Bytea data type.

This is my code :

models.py

class Question(models.Model):
    question_id = models.BigAutoField(primary_key=True)
    question = models.TextField(default=None, null=True)
    question_picture = models.BinaryField(default=None, null=True)
    answer = models.CharField(max_length=255)
    mc_a = models.CharField(max_length=255)
    mc_b = models.CharField(max_length=255)
    mc_c = models.CharField(max_length=255)

    class Meta:
        managed = True
        db_table = 'question'

    def __str__(self):
        return self.question

serializers.py

class QuestionSerializer(serializers.ModelSerializer):

    class Meta:
        model = Question
        fields = ('question_id',
                  'question',
                  'question_picture',
                  'answer',
                  'mc_a',
                  'mc_b',
                  'mc_c')

views.py

@api_view(['POST'])
def question_list(request):
    if request.method == 'POST':
            question_data = JSONParser().parse(request)
            questions_serializer = QuestionSerializer(data=question_data)
            if questions_serializer.is_valid():
                questions_serializer.save()
                return JsonResponse(questions_serializer.data, status=status.HTTP_201_CREATED) 
            return JsonResponse(questions_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

With the above code that I tried to run to insert data. When I checked the database, the question_picture data (image) was empty, but the other data was filled.

How do I insert the image so that it can be stored in the database?

1 Answer 1

0

How you send the image to Django? (Base64?).

I think this thread is similar to yours Serialize binary field django rest framework

Sign up to request clarification or add additional context in comments.

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.