我有这个型号:
fs = FileSystemStorage(location='/var/tmp/media/uploads/photos')
class Picture(models.Model):
""" vom user hochgeladenes bild """
image_field = models.ImageField(storage=fs)
user = models.ForeignKey('auth.User')
这种形式:
class PictureForm(ModelForm):
class Meta:
model = Picture
fields = ['user','image_field',]
但是当我尝试验证时,它将无效!
class PictureAddView(View):
def get(self,request):
picture_form = PictureForm()
context = {'picture_form': picture_form,}
return render(request, 'picturevault/picture_add.html', context)
def post(self,request):
from PIL import Image
Image.init()
picture_form = PictureForm(request.POST,request.FILES)
if picture_form.is_valid():
messages.add_message(request, messages.SUCCESS, 'picture link form valid')
else:
messages.add_message(request, messages.ERROR, 'picture link form invalid')
return HttpResponseRedirect(reverse('picturevault_picture_add_view'))
你能发现错误吗?
我得到的是'图片链接表单无效',这意味着它没有通过“picture_form.is_valid()”。
以下是模板:
{% extends 'base.html' %}
{% block content %}
<form method="POST" action="" >
{% csrf_token %}
{% for field in picture_form %}
{{ field }}
{% endfor %}
<input type="submit" value="submit" />
</form>
{% endblock %}
答案 0 :(得分:3)
我可以发现的第一件事是您在HTML enctype="multipart/form-data"
标记上遗漏了form
。没有它,你就无法通过表格上传文件(包括图片)。