Django模型实例 - 保存其他属性

时间:2016-01-21 06:42:46

标签: python django file-upload

我试图在我的Django应用程序中支持用户上传。应用程序应允许用户创建自己的文件和文件夹存储库。

以下是我的模型实例

class Project(models.Model):
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name

class Folders(models.Model):
    name = models.CharField(max_length = 255,default = 'Main')
    project = models.ForeignKey(Case)

class Files(models.Model):
    folder = models.ForeignKey(Folders)
    file = models.FileField(upload_to = get_upload_url)


def get_upload_url(instance,filename):
    print('Instance is :',instance)
    return '/'.join([instance.folder.project.name,instance.folder.name,filename])

当我尝试使用django表格将文档上传到特定文件夹时,我收到了错误

def ProjectPageAlt(request,casenum,folder):
    proj = Project.objects.get(pk=casenum)
    folder = Folders.objects.get(name = folder,project=proj)
    files = Files.objects.filter(folder=folder) or None

    if request.method == 'POST':
        form = FileUploadForm(request.POST,request.FILES)

        if form.is_valid():
            instance = form
            instance[folder] = folder
            # form.folder = folder
            instance.save()
            return HttpResponse('thanks')
    else:
        form = FileUploadForm()
    return render(request,'projectuploadalternative.html',{'form':form,'files':files})

我收到以下错误,因为我在保存之前尝试将文件夹实例添加到模型中

'FileUploadForm' object does not support item assignment

这周围有吗?我需要确保将文件上传到相应的文件夹

1 个答案:

答案 0 :(得分:0)

找到了解决方法。但这听起来更像是对我的黑客攻击。

def CasePageAlt(request,casenum,folder):
    case = Case.objects.get(pk=casenum)
    folder = Folders.objects.get(name = folder,case=case)
    files = Files.objects.filter(folder=folder) or None

    if request.method == 'POST':
        form = FileUploadForm(request.POST,request.FILES)

        if form.is_valid():
            file = request.FILES['upload']
            instance = Files(folder=folder,file=file)
            instance.save()
            return HttpResponse('thanks')
    else:
        form = FileUploadForm()
    return render(request,'caseuploadalternative.html',{'form':form,'files':files})

这是有效的,因为我的初始形式是ModelForm。现在我把表格变成了正常的表格

# class FileUploadForm(forms.ModelForm):
#
#     class Meta:
#         model = Files
#         fields = ['file']

class FileUploadForm(forms.Form):

    upload = forms.FileField()