Django使用提交按钮发布文本而不使用输入标记

时间:2018-04-06 10:21:53

标签: javascript html django django-templates jinja2

我有一个django模板,其中有一个表单,我从中获取用户的输入。

template.html

{% extends 'header.html' %}
{% load staticfiles %}

{% block content %}

    <h3> Questtion</h3>


    <img src="/media/{{ image }}" >
    <br> <br>
    <h3> Responses </h3>
<form  method="post" action="/tools/submit">
    {% csrf_token  %}
    <input type="text" name="first_response" placeholder="First Response"  size="40" required>
    <input type="text" name="second_response" placeholder="Second Response"  size="40" required> 
    <input type="text" name="third_response" placeholder="Third Response"  size="40" required> 
    <input type="text" name="fourth_response" placeholder="Fourth Response"  size="40" required>
    <input type="text" name="fifth_response" placeholder="Fifth Response"  size="40" required>

    <button type="submit" >Submit</button>
</form>   

{% endblock %}

views.py

中的以下方法很容易获得来自输入的文字
def post_form(request):
    if request.method == 'POST':
        first_response = request.POST.get('first_response')
        second_response = request.POST.get('second_response')
        third_response = request.POST.get('third_response')
        fourth_response = request.POST.get('fourth_response')
        fifth_response = request.POST.get('fifth_response')
        image_name = # HOW TO GET {{ image }} name here ?

但是,当我点击提交按钮时,我也想从<img src="/media/{{ image }}" >发布{{image}}。我怎样才能做到这一点 ?

2 个答案:

答案 0 :(得分:1)

in html

<form  method="post" action="/tools/submit" enctype="multipart/form-data">

<input type="file" name="image" placeholder="Image Response"  size="40" required>

在视图中

fifth_response = request.FILES.get('image')

答案 1 :(得分:1)

在html模板表单中添加此行

<input type="hidden" name="question" value="/media/{{ image }}">
在Django视图中

只需获取图像路径

fifth_response = request.POST.get('question')

由于图像已经在您的服务器上,我认为您不希望将其作为文件。所以获取文件路径就足够了。