简体   繁体   中英

This code is returning the error 'local variable 'name' referenced before assignment'.I am trying to keep a form and formset together

I am trying to make a form and formset work together which are not related to each other.Any suggestions if there are easy solutions to this?

def resume(request):
    form=ResumeForm(request.POST)
    ExperienceFormSet=formset_factory(Experience)
    formset=ExperienceFormSet(request.POST,request.FILES) 
    print(form.is_valid)
    if request.method=='POST':
        if form.is_valid() and formset.is_valid():
            name=request.POST.get('name')
            email=request.POST.get('email')
            phone=form.cleaned_data['phone']
            objective=request.POST.get('objective')
            branch=request.POST.get('branch')
            course=request.POST.get('course')
            course_total=course+' in '+branch
            department=request.POST.get('department')
            other_link=request.POST.get('other_link')
            for f in formset:
                cd=f.cleaned_data
                companyName=cd.get('companyName')
                print(companyName)
    else:
        form=ResumeForm()
        ExperienceFormSet=formset_factory(Experience)
        formset=ExperienceFormSet() 

    return render(request,'resume.html',{'name':name,'email':email,'phone':phone,'objective':objective,'course_total':course_total,'department':department,'other_link':other_link})

if request.method isn't 'POST', the variable name will never be created. Thus, when your function tries to return this part: {'name':name it won't find the variable name and it will fail.

These two lines might cause the problem:

if request.method=='POST':
    if form.is_valid() and formset.is_valid():

First if request.method is not a POST then the name variable will not be created thus name referenced before assignment error will occur. Same for second line of code too. You can solve this problem with like this:

if request_method=='POST':
        form_valid=form.is_valid()
        formset_valid=formset.is_valid()
        if form_valid and formset_valid:
            # ...
# ... 
if request_method=="POST" and form_valid and formset_valid:
        return render(request,'resume.html',{'name':name,'email':email,'phone':phone,'objective':objective,'course_total':course_total,'department':department,'other_link':other_link})
else:
   # Something is not valid you need to handle this.

There are quite a few things wrong with your view: you create a bound form right from the start (uselessly when it's a GET request), you use the raw request.POST data instead of the sanitized ones from the form's cleaned_data , and - the issue you mention - you try to inconditionnally use variables that are only conditionnally defined.

The proper canonical function-based-view template for form submissions is:

def myview(request):
   # if you have variables that you want to always
   # be in the context, the safest way is to define 
   # them right from the start (with a dummy value):

   name = None

   # now FIRST test the request method:
   if request.method == "POST":
       # and ONLY then build a bound form:
       form = MyForm(request.POST)
       if form.is_valid():
           # use sanitized data, not raw POST data:
           name = form.cleaned_data["name"]

   else:
      # build an unbound form
      form = MyForm()

   # here you know that both variables have been defined whatever
   return render(request, "mytemplate.html", {"form": form, "name": name}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM