Skip to content

Commit

Permalink
Custom file field with relative url
Browse files Browse the repository at this point in the history
  • Loading branch information
mmihalik committed Dec 14, 2024
1 parent 729501a commit b82594f
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
12 changes: 12 additions & 0 deletions base/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from rest_framework import fields


class RelativeUrlFileField(fields.FileField):
def to_representation(self, value):
request = self.context.pop('request', None)

representation = super().to_representation(value)

self.context['request'] = request

return representation
7 changes: 7 additions & 0 deletions competition/serializers.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from django.contrib.auth.models import AnonymousUser
from django.db.models import FileField
from django_typomatic import ts_interface
from rest_framework import serializers
from rest_framework.exceptions import ValidationError

from base.serializers import RelativeUrlFileField
from competition import models
from personal.serializers import ProfileShortSerializer, SchoolShortSerializer

Expand Down Expand Up @@ -42,6 +44,11 @@ class Meta:
model = models.Publication
fields = '__all__'

def __init__(self, instance=None, data=..., **kwargs):
super().__init__(instance, data, **kwargs)

self.serializer_field_mapping[FileField] = RelativeUrlFileField

def get_verbose_name(self, obj):
return str(obj)

Expand Down

0 comments on commit b82594f

Please sign in to comment.