I have a simple file model
class Documents(models.Model):
""" uploaded documents"""
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
upload = models.FileField(storage=PrivateMediaStorage())
filename = models.CharField(_('documents name'), max_length=255, blank=True, null=True)
datafile = models.FileField()
created = models.DateTimeField(auto_now_add=True)
type = models.ForeignKey(Doctype, on_delete=models.CASCADE, blank=True)
To display the list of uploaded documents and add new files, I use the class
class DocumentsListView(viewsets.ViewSetMixin,generics.ListCreateAPIView):
queryset = Documents.objects.all()
serializer_class = DocumentsSerializer
def perform_create(self, serializer):
serializer.save(author=self.request.user)
serializer.py
class DocumentsSerializer(AwsUrlMixin, serializers.ModelSerializer):
type_name = serializers.CharField(source='type.type', read_only=True)
type = serializers.PrimaryKeyRelatedField(queryset=Doctype.objects.all())
view_file = serializers.SerializerMethodField()
author = serializers.CharField(source='author.username', read_only=True)
created = serializers.DateTimeField(format=date_format, input_formats=None, default_timezone=None, read_only=True)
class Meta:
model = Documents
fields = ('id', 'author', 'filename', 'datafile', 'type', 'type_name', 'created', 'view_file')
I use the standard DRF interface and I display everything normally and add new files to the database.
While reading the documentation I came across parsers such as MultipartParser, FileUploadParser, which are also used when adding new files. I can't underatand when to use them and what function they perform, because now everything works without them.
The documentation hasn't given me a clear understanding of when I need to use parsers.
I try to add
parser_classes = (MultiPartParser, FileUploadParser)
to views.py and nothing change. Everything works as it did before. I'd appreciate it if you'd make that clear to me.
Parsers in Django REST are used to parse the content of incoming HTTP request. In HTTP request we receive the data as a string format. Parsers will parse the HTTP contents in to python data types based on the Content-Type header received in the HTTP request. Django REST Framework provides a number of built-in parsers which parses different types of contents like application/json
, multipart/form-data
, application/xml
, etc., based on the Content-Type header received in the HTTP request.
Parser Classes in Django REST:
JSONParser
FormParser
MultiPartParser
request.data
will be a QueryDict
containing all the form parameters.request.files
will be a QueryDict
containing all the form files.FileUploadParser
It is used to parse a single file sent in HTTP request.
It expects a url keyword argument "filename". If it's not provided then we should provide the filename in the Content-Disposition HTTP header. For example Content-Disposition: attachment; filename=upload.jpg.
request.file
is used to access the contents of uploaded file.
Reference: https://learnbatta.com/blog/parsers-in-django-rest-framework-85/
Parsers help your views to parse the data submitted in a specific format. Basically they map the Content-Type
header of the HTTP request to the code required to parse that type into a python structure that your Serializer
can understand.
If you're submitting content in the content types listed here, you don't need to do anything nor add any parser to your views. DRF already uses these parsers for these content types.
Only if your client is going to submit data in a different form, e.g. in XML or in yaml, will you need to add your own parser, many of which have already been written by someone else and can be found online. The reason adding the parsers you mentioned to your view doesn't do anything is that they are already the defaults used by DRF.
So let's say you have to integrate with an old-fashioned API (typically enterprises) that uses SOAP (God forbid...) then you'll have to bring in your own parser.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With