gpt4 book ai didi

python - Django文件上传: Upload form has no save method

转载 作者:太空宇宙 更新时间:2023-11-03 15:49:58 25 4
gpt4 key购买 nike

我遇到以下情况:

表单.py

class DocumentUploadForm(forms.Form):
file = forms.FileField(
validators=[validate_file_extension],
required=True
)
author = forms.CharField(required=True)

class Meta:
model = Document
fields = ['file', 'author']

模型.py

class Document(models.Model):
file = models.FileField(upload_to='documents/')
author = models.CharField(max_length=50)
date = models.DateField(auto_now=False, auto_now_add=True)
imported = models.BooleanField(default=False)

View .py

if request.method == "POST":
form = DocumentUploadForm(request.POST, request.FILES)

if form.is_valid():
# author = request.POST.get('author', None)
# if author is None:
# return HttpResponseRedirect("/")
# document = Document(file=request.FILES['file'], author=author)
# document.save()
form.save() # no save() method !!

错误:“DocumentUploadForm”对象没有“保存”属性

我不喜欢自己创建一个document对象并填写所有必要信息的方式。这会导致很多我不想要的错误处理。所以我看了一下https://docs.djangoproject.com/en/1.8/topics/http/file-uploads/#handling-uploaded-files-with-a-model

它们描述了我实现的确切方式,但我不知道为什么会出现 AttributeError。

任何帮助都会很好!阿罗纳达尔

最佳答案

您的表单似乎混合了 FormModelForm 代码,同时继承了基本的 Form (forms.Form)。 AFAIK,基本的 Django Form 没有 save() 方法。要使用简单的 form.save(),请使用 ModelForms。您已经在使用 Meta 类,因此您应该能够从 ModelForm 继承并删除表单的前两行:

class DocumentUploadForm(forms.ModelForm):
class Meta:
model = Document
fields = ['file', 'author']

有关更多信息,请参阅 ModelForm 文档:https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/以及这个问题的答案:object has no attribute 'save' Django

关于python - Django文件上传: Upload form has no save method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41409170/

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