DJANGO - local variable 'form' referenced before assignment

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

    The Django docs handle this, but slightly differently from the other answers. See https://docs.djangoproject.com/en/dev/topics/forms/#using-a-form-in-a-view

    Using an else, if the request is not POST then create the blank form. The below is pasted directly from the docs.

    def get_name(request):
        # if this is a POST request we need to process the form data
        if request.method == 'POST':
            # create a form instance and populate it with data from the request:
            form = NameForm(request.POST)
            # check whether it's valid:
            if form.is_valid():
                # process the data in form.cleaned_data as required
                # ...
                # redirect to a new URL:
                return HttpResponseRedirect('/thanks/')
    
        # if a GET (or any other method) we'll create a blank form
        else:
            form = NameForm()
    
        return render(request, 'name.html', {'form': form})
    

提交回复
热议问题