Reputation: 189
I am making django project and have one problem with uploading images in forms.
So, I tried to add one object with image, in admin this is working, but in form on site - not.
My views:
def newbook(request, user_id):
form = BookAdd(request.POST or None)
if form.is_valid():
book = form.save(commit=False)
book.author = get_object_or_404(User, pk=user_id)
book.save()
return redirect('../%s' % book.id)
return render(request, 'userbook/newbook.html', {'form': form})
My model:
class Book(models.Model):
"""Book is a compilation of sections with subjects."""
author = models.ForeignKey(AUTH_USER_MODEL)
name = models.CharField(max_length=100)
description = models.CharField(blank=True, max_length=256)
cover = models.ImageField(upload_to='img/bookcovers')
def __str__(self):
return self.name
My form:
class BookAdd(ModelForm):
class Meta:
model = Book
fields = ('name', 'description', 'cover')
When I add new book, I get an error "the field is required", maybe for field of cover, but image added. This work honestly on local server, but don't work on pythonanywhere.com
Upvotes: 0
Views: 77
Reputation: 6009
You have to change code
form = BookAdd(request.POST or None)
to
form = BookAdd(request.POST,request.FILES)
and your form should have enctype="multipart/form-data"
<form action="." method="post" enctype="multipart/form-data">
Upvotes: 4