1

So I'm working on a Django project and this is my views.py file:

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

When I ran my server, I got an error saying:

UnboundLocalError: local variable 'form' referenced before assignment

This is my new_topic.html file

{% 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 %}
1
  • Note that Django made a reference to this line: if form.is_valid(): Commented Dec 30, 2017 at 1:03

2 Answers 2

4

The line if form.is_valid(): fails on a GET request, because you're only defining form when request.method == 'POST'.

This can be fixed by changing some indentation:

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})
Sign up to request clarification or add additional context in comments.

Comments

0

I don't find any issue with indentation, but with initialization. Kindly initialize for before rendering it! Make changes as shown below will definitely work out and it's a very genuine and proper way to get rid of it:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.