我有一个用户个人资料,可以捕获用户名和分配给该用户的组。我希望上载的文件保存在组名文件夹下。文件夹已经从媒体根目录退出,应该将文件路由到这些文件夹
我通过给出的解决方案解决了这个问题。现在,用户名在上传页面上显示为下拉列表。我只希望显示登录的用户名,甚至不显示它
models.py
class uploadmeta(models.Model):
path = models.ForeignKey(Metadataform, on_delete=models.CASCADE)
user_profile = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, verbose_name='Username')
tar_gif = models.FileField(upload_to=nice_user_folder_upload, verbose_name="Dataset") # validators=[FileExtensionValidator(allowed_extensions=['tar', 'zip'])]
def __str__(self):
return self.request.user.username
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
Group= models.CharField(max_length=500, choices=Group_choices, default='Please Select')
def __str__(self):
return self.user.username
view.py
def uploaddata(request):
if request.user.is_authenticated:
if request.method == 'POST':
form = uploadmetaform(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('file_list')
else:
form = uploadmetaform()
return render(request, 'uploaddata.html', {
'form': form
})
else:
return render(request, 'home.html')
forms.py
class uploadmetaform(forms.ModelForm):
count = Metadataform.objects.all().latest('id').id #To know the id of latest object
data = Metadataform.objects.all().filter(id=count) #return the queryset with only latest object
path = forms.ModelChoiceField(queryset=data)
def __init__(self, *args, **kwargs):
super(uploadmetaform, self).__init__(*args, **kwargs)
count = Metadataform.objects.all().latest('id').id
data = Metadataform.objects.all().filter(id=count)
self.fields['path'] = forms.ModelChoiceField(queryset=data)
class Meta:
model = uploadmeta
fields = ['path', 'user_profile','tar_gif',]
答案 0 :(得分:1)
您可以在upload_to
中使用FileField
参数。
它接受一个表示您要存储文件路径的字符串,或者您可以传入一个可以添加更多详细信息的函数。
来自文档的更多信息:https://docs.djangoproject.com/fr/2.2/ref/models/fields/#django.db.models.FileField.upload_to
您可能需要将外键形式uploadmeta
添加到UserProfile
,例如:
user_profile = models.ForeignKey(UserProfile, on_delete=models.PROTECT)
然后您可以使用以下
def nice_user_folder_upload(instance, filename):
extension = filename.split(".")[-1]
return (
f"your_already_definied_folder/{instance.user_profile.group}/{file}.{extension}"
)
然后在uploadmeta
FileField
中使用它
doc = models.FileField(upload_to=nice_user_folder_upload, verbose_name="Dataset")