I have an issue with DRF file naming. The file of interest (I believe) is
serializers.py. What I want to occur when I upload a file is a creation of
a directory in the upload_to directory when the id of the object becomes
available. This is simple to do overriding the create method. What I have
not figured out how to do is to update the file in the database to reflect
the new path. It is easy to change the file to a string containing the
desired path for instance, but it is difficult to change the file to the
file with the desired path.
P.S. I am aware I am obscuring the file keyword. If necessary I will change
it.
Enter code here...
# models.py class TestFile(Model):
file = FileField(storage=FileSystemStorage(location=settings.MEDIA_ROOT),
upload_to='files', default='{}/files/empty.zip'.format(settings.MEDIA_ROOT))
created_at = CreationDateTimeField()
updated_at = ModificationDateTimeField()
def __str__(self):
return ''.join([str(self.file)])
def __unicode__(self):
return unicode(' '.join([str(self.id)]))
def __id__(self):
return str(self.id)
class Meta:
managed = True
db_table = 'test_files'
verbose_name_plural = 'Test Files'
# viewsets.pyclass TestFileViewSet(ModelViewSet):
queryset = TestFile.objects.all()
serializer_class = TestFileSerializer
parser_classes = (MultiPartParser, FormParser)
def perform_create(self, serializer):
serializer.save(file=self.request.data.get('file')
# serializers.pyclass TestFileSerializer(ModelSerializer):
file = serializers.FileField(required=True)
def create(self, validated_data):
# Calling create(), this will create the object in the database, making
the ID and PK of obj
# available to me.
obj = TestFile.objects.create(**validated_data)
# Creating a new path so that I can use a detail_route in viewset later
to GET file
new_path = '/'.join ([str(obj.file).split('/')[0],
str(obj.id),
str(obj.file).split('/')[1]])
# Try to create the parent directory of our destination. This shouldn't
fail
try:
os.mkdir(settings.MEDIA_ROOT+ '/files/' +str(obj.id), 0755 )
except:
pass
# Move old file to the new path that we just created.
shutil.copyfile(settings.MEDIA_ROOT + str(obj.file),
settings.MEDIA_ROOT + new_path)
# Remove the old file after we have already copied it to new destination
os.rmdir(settings.MEDIA_ROOT + str(obj.file))
# This is where the next step goes!
# What do I need to put in here to make obj.file the correct path now?
return obj
class Meta:
model = TestFile
fields = ( 'id','file','created_at','updated_at')
--
You received this message because you are subscribed to the Google Groups
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.