我刚刚写了一个自定义ImageField
(我真的不知道这种方式是否正确)。
代码如上:
from django.db import router
from django.contrib.auth.models import User
from django.db.models.fields.files import ImageField, FileField
def content_file_name(instance, filename):
return "/".join([router.db_for_read(User), # DATABASE ALIAS
instance._meta.app_label, # APP NAME
instance._meta.module_name, # MODEL NAME
filename]) # FILE NAME
class NMImageField(ImageField):
"""docstring for NMImageField"""
def __init__(self, *args, **kwargs):
kwargs['upload_to'] = content_file_name
super(NMImageField, self).__init__(*args, **kwargs)
我只想要一个具有默认upload_to
位置的ImageField。
长版:
from django.db import models
from django.db import router
from django.contrib.auth.models import User
from django.db.models.fields.files import ImageField, FileField
def content_file_name(instance, filename):
return "/".join([router.db_for_read(User), # DATABASE ALIAS
instance._meta.app_label, # APP NAME
instance._meta.module_name, # MODEL NAME
filename]) # FILE NAME
class AnyModel(models.Model):
Image = models.ImageField(upload_to=content_file_name)
我想做什么:
from django.db import models
from myproject.utils import NMImageField
class AnyModel(models.Model):
Image = NMImageField()
我不确定我做错了什么。