0

在 Django 中,我使用模型

class Specialist(models.Model):
    ...
    photo = models.ImageField(_('photo'), upload_to='spec_foto')
    ...

创建并保存新对象后,我在 .../spec_photo/filename.jpg 有“照片”字段但我想将文件移动到 .../spec_photo/ID/photo.jpg,其中 ID属于专家对象。为此,我重写了 Model.save 方法

def save(self):
    # Saving a new object and getting ID
    super(Specialist, self).save()
    # After getting ID, move photo file to the right destination
    # ????
    # Saving the object with the right file destination
    super(Specialist, self).save()

问题是,我应该怎么做才能移动文件?(???在代码中)。或者也许有更简单的方法?

4

2 回答 2

-1

您可以将其设置为可调用(即函数),而不是将“upload_to”设置为字符串,这将返回您需要的路径(https://docs.djangoproject.com/en/dev/ref/models/fields /#django.db.models.FileField.upload_to):

class Specialist(models.Model):
    ...
    photo = models.ImageField(_('photo'), upload_to=get_file_path)
    ...

def get_file_path(instance, filename):
    if not instance.id:
        instance.save()

    return 'spec_photo/%s/photo.jpg' % instance.id
于 2013-09-10T12:08:31.873 回答
-1

这是我的代码。
在模型.py

class ChatUser(models.Model):
"""User Model"""
username = models.CharField(max_length=64)
password = models.CharField(max_length=64)
GENDER_CHOICES = (
    (0, u'女'),
    (1, u'男')
)
sex = models.IntegerField(default=0, choices=GENDER_CHOICES)
description = models.CharField(max_length = 256, blank=True, default=None)
headphoto = models.ImageField(upload_to='photos/users/' , blank=True, default=None)

class Meta:
    db_table    = 'user'

def __unicode__(self):
    return "<ChatUser {'%s'}>" % self.username

在forms.py中

class UserForm(ModelForm):

    class Meta:
        model = ChatUser
        fields = ( 'username' , 'password' , 'sex' , 'description', 'headphoto')

和views.py

@csrf_exempt
def index(request):
    c = {}
    if request.method == 'POST':
        form = UserForm(request.POST , request.FILES)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']

            user = ChatUser.objects.filter( username = username, password = password )
            if user:
                print 'userhead ' , user[0].headphoto
                path = settings.WEB_BASE_PATH + '/' + str(user[0].headphoto)
                print path
                import os
                try:
                    os.remove( path )
                except:
                    pass
                import Image
                uploaded = request.FILES['headphoto']
                from django.core.files.base import ContentFile
                file_content = ContentFile(uploaded.read())
                user[0].headphoto.save( str(user[0].headphoto), file_content )
            else:
                form.save()
            return HttpResponseRedirect('thanks.html')
        else:
            print 'error ' , form.errors
    else:
        form = UserForm(initial={'username':'watsy', 'password':'123123'})
    c['form'] = form
    return render_to_response('index.html', c)
于 2013-09-10T12:09:45.263 回答