0

I was searching through stackoverflow for example of working fileupload APIView (using DRF of latest versions), I've already tried with many different code samples but none worked (some of them are deprecated, some - isn't what i want)

I have these models:

class Attachment(models.Model): type = models.CharField(max_length=15, null=False) attachment_id = models.CharField(max_length=50, primary_key=True) doc = models.FileField(upload_to="docs/", blank=True) 

I don't wanna use forms and anything else but rest parsers I want to get POST'ed fields (for example name) in future

I believe the solution is easy but this doesnt work

class FileUploadView(APIView): parser_classes = (FileUploadParser,) def post(self, request): file_obj = request.FILES doc = Attachment.objects.create(type="doc", attachment_id=time.time()) doc.doc = file_obj doc.save() return Response({'file_id': doc.attachment_id}, status=204) 
11
  • Doesnt work is not quite descriptive enough ... Commented Jul 9, 2018 at 23:36
  • @JoranBeasley in current example it says AttributeError at /file_upload/ 'dict' object has no attribute '_committed' Commented Jul 9, 2018 at 23:43
  • im posting file with header Content-Disposition: file; filename="test", the problem appears after .save() - I simply cant save file Commented Jul 9, 2018 at 23:45
  • files is a dict ... perhaps you want request.FILES['my_file'] Commented Jul 9, 2018 at 23:51
  • @JoranBeasley okay, then it writes with no file extension or broken Commented Jul 9, 2018 at 23:56

1 Answer 1

2

removing parser_class will solve almost all problems here. Try the following snippet

class FileUploadView(APIView): def post(self, request): file = request.FILES['filename'] attachment = Attachment.objects.create(type="doc", attachment_id=time.time(), doc=file) return Response({'file_id': attachment.attachment_id}, status=204) 


Screenshot of POSTMAN console
enter image description here

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.