Reputation: 9263
I got the following situation:
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 !!
Error: 'DocumentUploadForm' object has no attribute 'save'
I don't like the way by creating a document
object by my self and fill in all the necessary information. This leads to a lot of error handling that I don't want to have. So I had a look at https://docs.djangoproject.com/en/1.8/topics/http/file-uploads/#handling-uploaded-files-with-a-model
They describe the exact way I implemented but I don't know why I get the AttributeError.
Any help would be nice! aronadaal
Upvotes: 1
Views: 413
Reputation: 962
Your form seems to be mixing Form
and ModelForm
code, while inheriting from the basic Form (forms.Form)
. AFAIK, the basic Django Form
doesn't have a save()
method. To use a simple form.save()
, use ModelForms. You're using class Meta already, so you should be able to just inherit from ModelForm and remove the first two lines of your form:
class DocumentUploadForm(forms.ModelForm):
class Meta:
model = Document
fields = ['file', 'author']
See ModelForm docs for more: https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/ and also the answers to this question: object has no attribute 'save' Django
Upvotes: 1