是否有任何选项可以在views.py?
中获取ModelForm上传的新文件名我有这样的ModelForm。我想将用户上传的所有文件重命名为唯一名称,并按照本指南Enforce unique upload file names using django?
进行操作models.py
class SomePhotos(models.Model):
def get_file_path(instance, filename):
ext = filename.split('.')[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
return os.path.join('some_photos/', filename)
image = models.ImageField(upload_to = get_file_path)
link = models.URLField(verbose_name = u'URI', null = True, blank = True)
title_color = RGBColorField()
这很好用 - 文件作为唯一名称保存到右目录,但我在vievs.py中的功能停止工作,因为在独特重命名之前我一直在使用POST的文件名,但现在文件有其他唯一名称!
views.py
filename = request.FILES['image'].name
forms.py
class MotivatorForm(ModelForm):
class Meta:
model = SomePhotos
答案 0 :(得分:0)
保存ModelForm
后,您可以使用实例的.image.path
def myview(request):
if request.method == "POST":
form = MotivatorForm(request.POST, request.FILE)
if form.is_valid():
instance = form.save()
filepath = instance.image.path
# etc...