簡體   English   中英

無法從 Django 到 html 獲取數據

[英]can't get data from Django to html

視圖.py:

def index(request):
    if request.method == 'POST':
        data = request.POST['data']
        context = {'mydata': data}
        return render(request, 'home/index.html', context)
    else:
        html_template = loader.get_template('home/index.html')
        HttpResponse(html_template.render(request))

索引.html:

<form method = 'POST' id = 'post-form'>
      <select name = 'data' id = 'data'> 
        <option> 1 </option>
        <option> 2 </option>
      </select>
      <button type="submit" name = 'post-form'> submit </button>
</form>

<h2> {{ mydata}} </h2> // this line print nothing.

當我點擊提交按鈕時,我可以訪問來自html 提交到views.py 中的數據。

但是,我無法從 html 中的 Django 訪問mydata

我該如何解決?

代碼中有一些小錯誤:

  1. 你需要返回 HttpResponse 所以return HttpResponse(html_template.render(request)) ,但我建議你直接使用return render(request, 'home/index.html')

  2. 在處理表單內的 POST 數據時還需要放置{% csrf_token %} ,除非您在視圖中提到@csrf_exempt裝飾器。

所以,試試這個代碼:

視圖.py:


def index(request):
    if request.method == 'POST':
        data = request.POST.get('data')
        context = {'mydata': data}
        return render(request, 'home/index.html', context)
    else:
        return render(request, 'home/index.html')
                    # OR  #
        # html_template = loader.get_template('home/index.html')
        # return HttpResponse(html_template.render({}, request))

索引.html:

<form method='POST' id='post-form'>
    {% csrf_token %}
    <select name='data' id='data'> 
        <option> 1 </option>
        <option> 2 </option>
    </select>
    <button type="submit" name='post-form'> submit </button>
</form>
    
<h2> {{mydata}} </h2>

暫無
暫無

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

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