为什么我的视图不能正确加载?(Django)

2024-10-01 22:27:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Django的框架非常陌生,最近在他们的网站上完成了介绍性系列,我尝试添加一个新视图,在其中我使用表单创建对象

问题是,每当我访问该视图时,它都会立即执行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'))

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 %}

我试图这样做,如果我在问题文本输入中输入文本,当我单击提交按钮时,它会创建一个问题对象,问题文本是输入的文本,发布日期是当前时间

然而,它只是给出了一个失败的重定向

我不完全理解render()函数在视图中是如何工作的,以及它在逻辑中的位置如何影响视图的渲染,因此请原谅我的任何错误

我想知道为什么它不执行从submitbutton... else: 的任何代码,以及如何修复此问题以使视图按预期工作。如果有人能帮我解决渲染和视图问题,那就太好了

Error image


Tags: text文本视图fieldnewifrequestcreate
1条回答
网友
1楼 · 发布于 2024-10-01 22:27:07

这里使用的是递归

return HttpResponseRedirect(reverse('create'))

如果它失败了,它将再次重定向到这个Create函数,然后失败,再重定向,再重定向

试着这样做:

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)
    

相关问题 更多 >

    热门问题