我遇到以下情况:
forms.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']
models.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)
views.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' object has no attribute 'save'
我不喜欢通过自己创建document
对象并填写所有必要信息的方式。这导致了许多我不想要的错误处理。所以我看了https://docs.djangoproject.com/en/1.8/topics/http/file-uploads/#handling-uploaded-files-with-a-model
他们描述了我实施的确切方式,但我不知道为什么会出现AttributeError。
任何帮助都会很好! aronadaal
答案 0 :(得分:1)
您的表单似乎混合了Form
和ModelForm
代码,而继承自基本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