Django - 这个自定义FileField是正确的吗?

时间:2015-06-10 23:06:17

标签: django django-models

我刚刚写了一个自定义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()

我不确定我做错了什么。

0 个答案:

没有答案