上传到用户定义的文件夹Django

时间:2016-05-21 21:43:10

标签: python django amazon-web-services amazon-s3

我正在创建一个应用程序,用户可以将文件上传到AWS S3 Bucket。每个用户在注册时都会根据media userID文件夹获取None文件夹中的文件夹如何允许我的用户将项目上传到他们的文件夹中?文件上传得很好,但是文件名为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, } 。这似乎是一个简单的答案,但我似乎无法找到它。 这是我的views.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

这是我的models.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',
        ]

这是我的forms.py(以防万一)

{{1}}

2 个答案:

答案 0 :(得分:0)

将请求参数发送到您的modelForm init ..并使用它(假设您将有权访问request.user)来设置特定于该用户的位置字段

答案 1 :(得分:0)

问题在于你的models.py。

添加:

def fileLocation(instance, filename):
  return 'uploads/{0}/{1}'.format(instance.owner.username, os.path.basename(filename))

删除它:

fileLocation = None

并且您的用户文件应该进入uploads/<username>/<filename>

正如BobbyC所提到的,你应该使用ImageField而不是FileField