Django Rest Filefield保存在错误的URL下

时间:2019-06-26 12:46:33

标签: python django django-rest-framework

简单来说,我有一个带有附加Filefield的模型:

models.py
def uploadpath(instance, filename):
    return os.path.join('uploads/record/', filename)

class Measurement(models.Model):
    data = models.FileField(null=True, upload_to=uploadpath)

使用

MEDIA_URL = '/media/'
MEDIA_ROOT = '/vol/web/media'

和django rest序列化器

serializers.py
class MeasurementDataSerializer(serializers.ModelSerializer):

    class Meta:
        model = Measurement
        fields = ('id', 'data',)
        read_only_fields = ('id',)

如果我使用浏览器和djange rest界面上传文件,例如data.dat,它将正确返回数据的url:

"data": "http://localhost:8000/media/uploads/record/data.dat"

但是,有时我会在外壳中手动创建模型:

with NamedTemporaryFile() as tmp_file:
    filepath = "/vol/web/media/uploads/record/data.dat"
    some_measurement.data.save(filepath, tmp_file, save=True)

并在浏览器中列出所有度量,它返回错误的URL:

http://localhost:8000/media/vol/web/media/uploads/record/data.dat"

在这种情况下,我必须如何调整文件的手动创建,以使URL正确

"data": "http://localhost:8000/media/uploads/record/data.dat"

返回了吗?

0 个答案:

没有答案