我试图从输入ImageFile中获取图像以显示在模板中,并将ImageFile保存到模型ImageField中。
下面的代码吐出错误:
upload_img_temp.write(uploaded_image)
TypeError: a bytes-like object is required, not 'str'
表格
class UploadImageForm(forms.ModelForm):
class Meta:
model = Image
fields = ['image']
查看
def uploadImageView(request):
form = UploadImageForm(request.POST or None, request.FILES or None)
if request.method == 'POST':
if form.is_valid:
request.session['image'] = request.POST['image']
return redirect('image:create')
def imageCreateView(request):
uploaded_image = request.session.get('image')
upload_img_temp = NamedTemporaryFile()
upload_img_temp.write(uploaded_image)
upload_img_temp.flush()
form_create = ImageModelCreateForm(request.POST or None, request.FILES or None,)
if form_create.is_valid():
instance = form_create.save(commit=False)
instance.image = upload_img_temp
模板
<img class="image" src="{{ upload_img_temp }}">
<form method="POST" action="">
{% csrf_token %}
<input type="submit"></input>
{{ form }}
</form>
模型
def upload_location(instance, filename):
filebase, extension = filename.split(".")
return "%s/%s.%s" %('picx', uuid.uuid4(), extension)
class Image(models.Model):
image = models.ImageField(
upload_to=upload_location,
null=False,
blank=False,
)
答案 0 :(得分:2)
所以你有很多问题。
<form method="POST" action="" enctype='multipart/form-data' >
您需要在enctype='multipart/form-data'
中添加form
,否则将不接受任何文件。
<img class="image" src="{{Image.image.url}}">
注意&#34;图像&#34;需要是您在此模板的views.py上下文部分中定义的有效参数。它是对你的模型和第二个&#34;图像的参考。关键字是指您的模型属性&#34;图像&#34;。 .url
是必需的。将views.py更改为类似的内容:
def uploadG(request):
form = PostForm(request.POST or None, request.FILES or None)
if form.is_valid():
print ("form was valid TEST") #controll your console and check if that statement appears when you click upload.
instance = form.save(commit = False)
....
instance.save()
messages.success(request, 'You uploaded it')
希望有所帮助。如果没有发表评论
答案 1 :(得分:0)
您是否希望在用户实际点击之前显示图片&#34;提交&#34;你的表格按钮?
为此你可能应该考虑处理ajax请求。
如果您只想在页面上显示图片,例如你想上传它,把它保存到你的数据库,然后从数据库中取出它并把它放在模板中,你应该只是呼叫&#34; url&#34;图像字段的属性。
例如: 您有模型,如:
class ProductImage(models.Model):
image = models.ImageField(
upload_to=upload_location,
null=False,
blank=False,
)
您已将图像保存在数据库中。
要将其从数据库传递到模板,您应该在视图中执行类似的操作:
p_image = ProductImage.objects.get(id=3)
context['product_image'] = p_image
return render (request, 'template.html', context)
然后在模板:
中<img class="product-image" src="{{ product_image.image.url }}"/>
实际上,使用Ajax几乎是一样的,只有你应该通过javascript发送你的表单和更新页面。