gpt4 book ai didi

Django动态FileField upload_to

转载 作者:行者123 更新时间:2023-12-03 16:30:14 25 4
gpt4 key购买 nike

我正在尝试为FileField模型创建动态上载路径。因此,当用户上传文件时,Django将其存储到我的计算机/media/(用户名)/(path_to_a_file)/(文件名)中。

例如。/media/Michael/Homeworks/Math/Week_1/questions.pdf或/media/Ernie/Fishing/Atlantic_ocean/Good_fishing_spots.txt

VIEWS
@login_required
def add_file(request, **kwargs):
if request.method == 'POST':
form = AddFile(request.POST, request.FILES)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user

post.parent = Directory.objects.get(directory_path=str(kwargs['directory_path']))
post.file_path = str(kwargs['directory_path'])

post.file_content = request.FILES['file_content'] <-- need to pass dynamic file_path here

post.save()
return redirect('/home/' + str(post.author))

MODELS
class File(models.Model):
parent = models.ForeignKey(Directory, on_delete=models.CASCADE)
author = models.ForeignKey(User, on_delete=models.CASCADE)
file_name = models.CharField(max_length=100)
file_path = models.CharField(max_length=900)
file_content = models.FileField(upload_to='e.g. /username/PATH/PATH/..../')

FORMS
class AddFile(forms.ModelForm):
class Meta:
model = File
fields = ['file_name', 'file_content']

我发现的是这个,但是经过反复试验,我还没有找到解决方法。因此,“upload/...”将是post.file_path,这是动态的。
def get_upload_to(instance, filename):
return 'upload/%d/%s' % (instance.profile, filename)


class Upload(models.Model):
file = models.FileField(upload_to=get_upload_to)
profile = models.ForeignKey(Profile, blank=True, null=True)

最佳答案

您可以使用类似这样的东西(我在我的项目中使用过):

import os
def get_upload_path(instance, filename):
return os.path.join(
"user_%d" % instance.owner.id, "car_%s" % instance.slug, filename)

现在:
photo = models.ImageField(upload_to=get_upload_path)

关于Django动态FileField upload_to,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50591304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com