0

I use django-rest-framework first time. I use json format by default. I need to send file for creating a new instance. This file has being saved in models.ImageField. However, I don't know which format this field requires for incoming file. I tried to send it in base64, but it isn't suitable.

TestCase for this problem:

class PersonTestCase(APITestCase):
    def setUp(self):
        self.c = APIClient()

    def test_sign_up_with_valid_data(self):
        with open('persons/test/bg.jpg', 'rb') as bg:
            valid_registration_data = {
                ...,
                'background': base64.b64encode(bg.read()).decode('utf-8'),
            }
            response = self.c.post('/persons/sign_up', valid_registration_data)
            self.assertEqual(response.status_code, 201)
            self.assertEqual(Person.objects.count(), 1)
            self.assertEqual(Person.objects.get('username'), 'test_client74562984')

View:

class SignUpView(APIView):
    """
    Create new user
    """
    def post(self, request):
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            response = Response(serializer.data, status=status.HTTP_201_CREATED)
            return response
        response = Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        return response
Alexander Shpindler
  • 811
  • 1
  • 11
  • 31
  • How is the receiver expecting the file to be sent? You most likely would need to send it as a multipart post request http://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file – serg Apr 29 '17 at 17:05
  • @serg I added the view which receives this data. I forgot to mention that I use django-rest-framework. Serializer object waits data in JSON format, and then it saves it as model's object. – Alexander Shpindler Apr 30 '17 at 00:26

0 Answers0