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 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.