0

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

1 Answers1

4

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">
Geo Jacob
  • 5,909
  • 1
  • 36
  • 43
  • Thank you very much it is working, file uploaded without problems. But now form shows the field is required at once, it must be so? – Dmitriy Kuzminov Aug 31 '15 at 04:36
  • your field should be null=True,blank=True ex:cover = models.ImageField(upload_to='img/bookcovers',null=True,blank=True) – Geo Jacob Aug 31 '15 at 04:40