I am having trouble uploading the image field on my model form.
views.py:
@user_passes_test(lambda x: x.is_superuser)
def add_books(request):
if request.method == 'POST':
form = BooksForm(request.POST, request.FILES)
if form.is_valid():
form.save()
redirect('/')
else:
form = BooksForm()
return render(request, 'library/books/addbook.html', {'form': form})
models.py:
class Books(models.Model):
picture = models.ImageField(upload_to='images/')
name = models.CharField(max_length=100)
publisher = models.CharField(max_length=200)
author = models.CharField(max_length=100)
member = models.ForeignKey(Member, related_name="books", null=True)
def get_absolute_url(self):
return reverse('library:detail_book', kwargs={'book_id': self.id})
def __unicode__(self):
return "%s %s" % (self, self.name, self.author)
def __str__(self):
return "{0} {1}".format(self.name, self.author)
forms.py:
class BooksForm(ModelForm):
class Meta:
model = Books
fields = ('picture', 'name', 'publisher', 'author')
def clean_name(self):
name = self.cleaned_data['name']
if Books.objects.filter(name=name).exists():
raise ValidationError("A Book with that name already exists!")
return name
addbook.html:
{% extends "library/base.html" %}
{% block content %}
<div align="center">
<tr>
<form method="POST">
{% csrf_token %}
<h2>Book:</h2>
{{ form.as_p }}
<input type="submit" value="submit">
</form>
</tr>
</div>
{% endblock %}
settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
Once, I try to add a book and i add the image field and hit the button, the form tells me that the image field is required and it does not let me upload the image. Thank you ahead for your help!
To upload files in your form you need to add the following attribute to the form element:
<form method="POST" enctype="multipart/form-data">
Without this, the file is not being uploaded, which is why Django's form API is raising an error (as it is a required field).