[英]Django-rest-framework: Browsable API can't get POST data via HTML form, but can from Raw data
[英]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
。
我該如何解決?
代碼中有一些小錯誤:
你需要返回 HttpResponse 所以return HttpResponse(html_template.render(request))
,但我建議你直接使用return render(request, 'home/index.html')
。
在處理表單內的 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.