Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DJANGO - local variable 'form' referenced before assignment

I'm trying to make a form get information from the user and use this information to send a email. Here's my code:

#forms.py
from django import forms

class ContactForm(forms.Form):
    nome = forms.CharField(required=True)
    email = forms.EmailField(required=True)
    msg = forms.CharField(
        required=True,
        widget=forms.Textarea
    )

#views.py
from django.shortcuts import render, redirect, get_object_or_404, HttpResponseRedirect, render_to_response
from django.core.mail import send_mail
from .forms import ContactForm

def contato(request):
    form_class = ContactForm
    if request.method == 'POST':
        form = form_class(request.POST)
        if form.is_valid():
            nome = request.POST.get('nome')
            email = request.POST.get('email')
            msg = request.POST.get('msg')

            send_mail('Subject here', msg, email, ['[email protected]'], fail_silently=False)
            return HttpResponseRedirect('blog/inicio')
    return render(request, 'blog/inicio.html', {'form': form})


#contato.html
{% extends "blog/base.html" %}
{% block content %}

                    <form role="form" action="" method="post">
                        {% csrf_token %}
                        {{ form.as_p }}
                        <button type="submit">Submit</button>
                    </form>
{% endblock %}

and when I try to enter in contact page I get this error:

local variable 'form' referenced before assignment

enter image description here

It is saying tha the error is in this line of views.py:

return render(request, 'blog/inicio.html', {'form': form})

I'm a little new on Django, can you please help me?

like image 768
Guilherme Pedro Avatar asked Mar 02 '16 13:03

Guilherme Pedro


1 Answers

You define the form variable in this if request.method == 'POST': block. If you access the view with a GET request form gets not defined. You should change the view to something like this:

def contato(request):
    form_class = ContactForm
    # if request is not post, initialize an empty form
    form = form_class(request.POST or None)
    if request.method == 'POST':

        if form.is_valid():
            nome = request.POST.get('nome')
            email = request.POST.get('email')
            msg = request.POST.get('msg')

            send_mail('Subject here', msg, email, ['[email protected]'], fail_silently=False)
            return HttpResponseRedirect('blog/inicio')
    return render(request, 'blog/inicio.html', {'form': form})
like image 151
ilse2005 Avatar answered Sep 24 '22 18:09

ilse2005