[英]Uploading to User Defined Folders Django
I am making an app where users can upload files to an AWS S3 Bucket. 我正在创建一个应用程序,用户可以将文件上传到AWS S3 Bucket。 Each user, when signing up, gets a folder within the
media
folder based on their userID
How to I allow my users to upload their projects to that their folders? 注册时,每个用户都会根据
userID
获取media
文件夹中的文件夹如何允许我的用户将他们的项目上传到他们的文件夹? The files upload just fine, but to a folder named None
. 文件上传得很好,但是文件名为
None
。 This seems like an easy answer, but I cannot seem to find it. 这似乎是一个简单的答案,但我似乎无法找到它。 Here's my views.py
这是我的views.py
def new(request):
title = "Add New Project"
if not request.user.is_authenticated():
raise Http404
form = ProjectForm(request.POST or None, request.FILES or None)
if form.is_valid():
instance = form.save(commit=False)
instance.fileLocation = request.user.id
instance.user = request.user
instance.save()
return redirect("/dashboard/")
context = {
"form": form,
"title": title,
}
Here's my models.py 这是我的models.py
from django.db import models
from django.conf import settings
# Create your models here.
class Project(models.Model):
fileLocation = None
user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True)
title = models.CharField(max_length=200)
description = models.TextField()
sell = models.BooleanField(default=False)
timestamp = models.DateTimeField(auto_now_add=True)
image = models.FileField(upload_to=fileLocation, null=True, blank=True)
def __str__(self):
return self.title
And here's my forms.py (just in case) 这是我的forms.py(以防万一)
from django import forms
from .models import Project
from django.contrib.auth.models import User
class ProjectForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ProjectForm, self).__init__(*args, **kwargs)
self.fields['image'].required = True
class Meta:
model = Project
fields = [
'title',
'description',
'image',
'sell',
]
将请求参数发送到您的modelForm init ..并使用它(假设您将有权访问request.user)来设置特定于该用户的位置字段
The issue is in your models.py. 问题出在你的models.py中。
Add this: 添加这个:
def fileLocation(instance, filename):
return 'uploads/{0}/{1}'.format(instance.owner.username, os.path.basename(filename))
remove this: 删除这个:
fileLocation = None
and your user's file should go into uploads/<username>/<filename>
. 并且您的用户文件应该进入
uploads/<username>/<filename>
。
As BobbyC mentioned, you should use ImageField instead of FileField 正如BobbyC所提到的,你应该使用ImageField而不是FileField
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.