簡體   English   中英

Django使用提交按鈕而不使用輸入標簽發布文本

[英]Django post text using submit button without using input tag

我有一個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 }}" > 我怎樣才能做到這一點 ?

在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')

在您的html模板表單中添加此行

<input type="hidden" name="question" value="/media/{{ image }}">

在Django視圖中只需獲取圖像路徑

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

由於該圖像已經在您的服務器上,因此我不希望您將其作為文件保存。 因此獲取文件路徑就足夠了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM