我想从ImageField
文件输入中获取图像,然后在模板中显示图像,最后将图像保存到模型imageField
。
file_image = request.POST.get('image')
只获取图片名称,如何获取实际图片。我是否需要先将图片上传到NamedTemporaryFile()
?
查看
def uploadImageView(request):
form = UploadImageForm(request.POST or None, request.FILES or None)
if request.method == 'POST':
if form.is_valid:
file_image = request.POST.get('image')
request.session['file_image'] = file_image
return redirect('image:create')
def saveImageView(request):
uploaded_image = request.session.get('file_image')
form = Form(request.POST or None, request.FILES or None,)
if form.is_valid():
instance = form_create.save(commit=False)
instance.image = uploaded_image
inastance.save()
模板
首次观看模板
<form method="POST" action="">
{% csrf_token %}
<input type="submit"></input>
{{ form }}
</form>
第二次观看模板
<form method="POST" action="">
{% csrf_token %}
{{ form }}
<input type="submit"></input>
</form>
{{ form.instance.image.url }}
答案 0 :(得分:1)
要获取在html文件中输入的图像, 使用:
request.FILES["input name "]
答案 1 :(得分:0)
要上传文件,您需要将enctype='multipart/form-data'
添加到HTML表单中。因此您的表单应如下所示:
<form method="POST" action="" enctype='multipart/form-data'>
{% csrf_token %}
<input type="submit"></input>
{{ form }}
</form>
,并且在您的视图中,您需要访问request.FILES
才能获取上载的文件。您的上传图片视图应为:
def uploadImageView(request):
form = UploadImageForm(request.POST or None, request.FILES or None)
if request.method == 'POST':
if form.is_valid():
form.save()
# rest of the code.