像这样的东西应该工作。
from modeltranslation.translator import translator
from django.db.models import FileField
import os
class TranslationMeta(type):
def __init__(self, name, bases, attrs):
for attrname, attrvalue in attrs.items():
if self.is_translated_field(name, attrname):
field = attrvalue
if isinstance(field, FileField):
self.update_upload_to(field, attrname)
super().__init__(name, bases, attrs)
def is_translated_field(self, class_name, attr_name):
opts = translator.get_options_for_model(self)
return attr_name in opts.get_field_names()
def update_upload_to(self, field, attr_name):
opts = translator.get_options_for_model(self)
translated_fields = opts.fields[attr_name]
for trans_field in translated_fields:
# print(trans_field.name)
# print(trans_field.language)
trans_field.upload_to = self.custom_upload_to(field.upload_to, trans_field.language)
def custom_upload_to(self, base_upload_to, language):
# If the original upload_to parameter is a callable,
# return a function that calls the original upload_to
# function and inserts the language as the final folder
# in the path
# If the original upload_to function returned /path/to/file.png,
# then the final path will be /path/to/en/file.png for the
# english field
if callable(base_upload_to):
def upload_to(instance, filename):
path = base_upload_to(instance, filename)
return os.path.join(
os.path.dirname(path),
language,
os.path.basename(path))
return upload_to
# If the original upload_to parameter is a path as a string,
# insert the language as the final folder in the path
# /path/to/file.png becomes /path/to/en/file.png for the
# english field
else:
return os.path.join(
os.path.dirname(base_upload_to),
language,
os.path.basename(base_upload_to))
# This is how you would use this class
class MyModel(models.Model, metaclass=TranslationMeta):
field = FileField()
m = MyModel(models.Model)
print(m.field.upload_to)
它使用自省来动态覆盖upload_to
由 django-modeltranslation 在后台生成的每个特定语言的 FileField 的参数。
以这个模型为例:
class MyModel(models.Model):
field = FileField(upload_to=...)
如果您已field
通过添加定义为可翻译字段
from modeltranslation.translator import register, TranslationOptions
from . import models
@register(models.MyModel)
class MyModelTranslationOptions(TranslationOptions):
fields = ("field",)
在translation.py
,django-modeltranslation 将生成类似
class MyModel(models.Model):
field = FileField(upload_to=...)
field_en = FileField(upload_to=...)
field_fr = FileField(upload_to=...)
如果您有en
并fr
在您的LANGUAGES
设置中定义。
如果upload_to
传递给 FileField 的参数是作为字符串的路径,则它会被插入该语言的文件夹的相同路径覆盖。如果它是一个函数,则该语言的文件夹将插入该函数返回的路径中。
例如,如果你有
class MyModel(models.Model):
field = FileField(upload_to="/path/to/file.png")
或者
def get_upload_path(instance, filename):
return "path/to/file.png"
class MyModel(models.Model):
field = FileField(upload_to=get_upload_path)
那么,在这两种情况下:
- 文件的英文版本将存储在 /path/to/en/file.png
- 该文件的法语版本将存储在 /path/to/fr/file.png