首页 > 解决方案 > 此代码返回错误“分配前引用的局部变量“名称”。我正在尝试将表单和表单集保持在一起

问题描述

我正在尝试使彼此不相关的表单和表单集一起工作。如果有简单的解决方案,有什么建议吗?

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})

标签: pythondjangodjango-forms

解决方案


您的观点有很多问题:您从一开始就创建了一个绑定表单(当它是一个 GET 请求时无用),您使用原始request.POST数据而不是表单中经过清理的数据cleaned_data,并且 - 您提到的问题 -您尝试无条件地使用仅按条件定义的变量。

表单提交的正确规范的基于函数的视图模板是:

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}

推荐阅读