python - 此代码返回错误“分配前引用的局部变量“名称”。我正在尝试将表单和表单集保持在一起
问题描述
我正在尝试使彼此不相关的表单和表单集一起工作。如果有简单的解决方案,有什么建议吗?
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})
解决方案
您的观点有很多问题:您从一开始就创建了一个绑定表单(当它是一个 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}
推荐阅读
- node.js - 续集 createdAt 和 updatedAt
- javascript - 如何使用 Angular 4 及更高版本实现 JSON Schema Faker
- amazon-web-services - 尝试通过 .net 在 cognito 中建立用户时如何修复请求超时
- amazon-web-services - 带有前缀和分隔符的 boto s3 存储桶对象过滤器
- node.js - 使用 Google Actions 保持用户和代理之间的聊天
- android - 慢慢滚动页面
- reactjs - 在 React 应用程序中启用 CORS 的最佳方法是什么?
- python - 使用 AWS ElasticSearch 服务实例将包含地理纬度和纬度的两个浮点字段映射到 kibana 中的 geo_point
- mysql - MySQL 位数据类型的 Django 等效项
- excel - 为什么 Range.FindNext 不继承参数?