繁体   English   中英

为什么我的视图无法正确加载? (姜戈)

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM