gpt4 book ai didi

python - 未绑定(bind)本地错误 : local variable 'form' referenced before assignment in Django

转载 作者:太空宇宙 更新时间:2023-11-04 09:50:22 25 4
gpt4 key购买 nike

所以我正在做一个 Django 项目,这是我的 views.py 文件:

def new_topic(request, pk):
board = get_object_or_404(Board, pk=pk)
user = User.objects.first() # TODO: get the currently logged in user

if request.method == 'POST':
form = NewTopicForm(request.POST)
if form.is_valid():
topic = form.save()
return redirect('board_topics', pk=board.pk)
else:
form = NewTopicForm()
return render(request, 'new_topic.html', {'form': form})

当我运行我的服务器时,我收到一条错误消息:

UnboundLocalError:赋值前引用了局部变量“form”

这是我的new_topic.html 文件

{% extends 'base.html' %}

{% block title %}Start a New Topic{% endblock %}

{% block breadcrumb %}
<li class="breadcrumb-item"><a href="{% url 'home' %}">Boards</a></li>
<li class="breadcrumb-item"><a href="{% url 'board_topics' board.pk %}">{{ board.name }}</a></li>
<li class="breadcrumb-item active">New topic</li>
{% endblock %}

{% block content %}
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-success">Post</button>
</form>
{% endblock %}

最佳答案

if form.is_valid(): 行在 GET 请求上失败,因为当 时您只定义了 form request.method == 'POST'.

这可以通过更改一些缩进来解决:

if request.method == 'POST':
form = NewTopicForm(request.POST)
if form.is_valid():
topic = form.save()
return redirect('board_topics', pk=board.pk)
else:
form = NewTopicForm()
return render(request, 'new_topic.html', {'form': form})

关于python - 未绑定(bind)本地错误 : local variable 'form' referenced before assignment in Django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48029861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com