[英]Why won't my view load in properly? (Django)
我對 Django 的框架非常陌生,最近完成了他們網站上的介紹系列,我嘗試添加一個新視圖,在該視圖中我使用表單創建 object。
問題是,每當我訪問視圖時,它都會立即執行 HttpResponseRedirect(),其次它甚至不返回響應。
視圖.py
def create(request):
context = {
'questionfields': Question.__dict__,
}
submitbutton = request.POST.get('Create', False)
if submitbutton:
new_question = Question(question_text=request.POST.get('question_text', ''), pub_date=timezone.now())
if new_question.question_text == '':
context = {
'questionfields': Question.__dict__,
'error_message': "No poll question entered."
}
del new_question
return render(request, 'polls/create.html', context)
else:
return HttpResponseRedirect(reverse('create'))
創建.html
{% extends "polls/base.html" %}
{% block title %}Create a Poll{% endblock title %}
{% block header %}Create:{% endblock header %}
{% load custom_tags %}
{% block content %}
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'polls:create' %}" method="post"> {% csrf_token %}
{% for field in questionfields %}
{% if field == 'question_text' %}
<label for="{{ field }}">{{ field|capfirst|replace }}:</label>
<input type="text" name="{{ field }}" id="{{ field }}">
<br>
{% else %}
{% endif %}
{% endfor %}
<br>
<input type="submit" value="Create" name="submit">
</form>
{% endblock content %}
我試圖這樣做,如果我在 question_text 輸入中輸入文本,當我單擊提交按鈕時,它會創建一個 Question object,其中 question_text 是輸入的文本,pub_date 是當前時間。
但是,它只是給出了一個失敗的重定向。
我不完全理解 render() function 如何在視圖中工作,以及它在邏輯中的位置如何影響視圖的渲染,所以請原諒我的任何錯誤。
我想知道為什么它不執行從submitbutton...
到else:
的任何代碼,以及如何解決這個問題以使視圖按預期工作。 如果有人可以幫助解決我的渲染和查看問題,那就太好了。
你在這里使用遞歸
return HttpResponseRedirect(reverse('create'))
萬一失敗,它會再次重定向到這個 Create function ,失敗,再次重定向,再次......
嘗試這樣做:
def create(request):
context = {
'questionfields': Question.__dict__,
}
submitbutton = request.POST.get('Create', False)
if submitbutton:
new_question = Question(question_text=request.POST.get('question_text', ''), pub_date=timezone.now())
if new_question.question_text == '':
context = {
'questionfields': Question.__dict__,
'error_message': "No poll question entered."
}
del new_question
# Just render the page here with the initial context
return render(request, 'polls/create.html', context)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.