gpt4 book ai didi

python - Django : Why does my image field form not validate?

转载 作者:行者123 更新时间:2023-11-30 23:20:04 24 4
gpt4 key购买 nike

我有这个模型:

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 %}

最佳答案

我发现的第一件事是您的 HTML form 标记上缺少 enctype="multipart/form-data"。否则,您将无法通过表单上传文件(包括图像)。

关于python - Django : Why does my image field form not validate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25724120/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com