Python 如何将新django模型对象的文件字段保存到ID为的路径?
在Django中,我使用模型Python 如何将新django模型对象的文件字段保存到ID为的路径?,python,django,model,filefield,imagefield,Python,Django,Model,Filefield,Imagefield,在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(se
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()
问题是,我应该做什么来移动文件???在代码中。或者有更简单的方法吗?您可以将其设置为可调用的ie函数,该函数将返回所需的路径,而不是将“upload\u to”设置为字符串: 这是我的密码。 在models.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
和视图.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)
我不认为您可以这样做,您的第二次保存将再次将其带回upload_to参数返回的路径。因此,您将有2个文件副本,但其中一个../ID/。。将不被使用。请尝试以下操作:obj=supercialist,self.save在save内的第一个调用中此代码不能解决我的问题。新创建的对象没有ID。
class UserForm(ModelForm):
class Meta:
model = ChatUser
fields = ( 'username' , 'password' , 'sex' , 'description', 'headphoto')
@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)