DJANGO - local variable 'form' referenced before assignment

前端 未结 4 1709
轮回少年
轮回少年 2021-02-09 09:54

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 Con         


        
4条回答
  •  我寻月下人不归
    2021-02-09 10:56

    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, ['testmail@gmail.com'], fail_silently=False)
                return HttpResponseRedirect('blog/inicio')
        return render(request, 'blog/inicio.html', {'form': form})
    

提交回复
热议问题