UnboundLocalError:局部变量'形式'在Django中赋值之前引用

时间:2017-12-30 00:35:28

标签: python django django-views

所以我正在研究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: local variable 'form' referenced before assignment

这是我的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 %}

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:0)

我发现缩进没有任何问题,但有初始化问题。请在渲染之前进行初始化!进行如下所示的更改绝对可以解决问题,这是摆脱它的一种非常真实而正确的方法:

def new_topic(request, pk):
    board = get_object_or_404(Board, pk=pk)
    user = User.objects.first()  # TODO: get the currently logged in user
    form = NewTopicForm()
    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})