DJANGO - local variable 'form' referenced before assignment

前端 未结 4 1693
轮回少年
轮回少年 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:50

    If there can be so to say - "collateral damage" by initializing an empty "form" , then you may also provide a "dummy" value as a filler , till the "request.POST" is initialized ...

    def contato(request):
    form = "Dummy String"
    form_class = ContactForm
    # if request is not post, initialize an empty form
    #form = form_class(request.POST or None) # Maybe Not 
    form = form_class(request.POST ) # Instead 
    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})
    

提交回复
热议问题