我在模型表单上上传图片字段时遇到问题。
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/')
有一次,我尝试添加一本书,然后添加图像字段并按下按钮,表单告诉我图像字段是必需的,它不允许我上传图像。谢谢你的帮助!
答案 0 :(得分:0)
要上传表单中的文件,您需要将以下属性添加到表单元素:
<form method="POST" enctype="multipart/form-data">
没有这个,文件没有被上传,这就是Django的表单API引发错误的原因(因为它是必填字段)。