Django风险评分问卷应用AttributeError问题及分数输出需求
解决Django表单向导AttributeError问题并实现分数计算输出
问题背景
刚入门Django,开发风险承受能力评分问卷应用,使用表单向导(SessionWizardView)时出现错误:AttributeError: type object 'Questiontwo' has no attribute 'question2',同时需要实现提交后在HttpResponse页面输出分数。
错误原因
- 表单字段访问方式错误:在
done方法中直接通过Questiontwo.question2访问表单字段,question2是表单实例的属性,而非类属性,直接访问类会触发AttributeError。 - 模型字段赋值逻辑错误:在
Questiontwo表单类中直接执行Risk_Profile.score_risk_toler=question2,属于无效赋值,模型字段的赋值应在视图处理提交数据时完成。 - 模型导入不完整:
views.py中from .models import语句没有指定具体模型,导致无法操作数据库。 - 表单初始化方法错误:
Questionnine类的__init__方法覆盖了默认参数,会导致表单初始化失败。
修复步骤
步骤1:修正forms.py代码
- 删除
Questiontwo类中错误的模型赋值语句 - 修复
Questionnine的初始化方法,保留默认表单初始化逻辑 - 修正
Questionnine的label文本(原label与问题不符)
修正后的forms.py关键部分:
class Questiontwo(forms.Form): # Risk TOLERANCE choice = ((0, "No."), (7, "Some"), (11, "Good"), (15,"Extensive")) question2= forms.TypedChoiceField(choices= choice, coerce=int, label="What is your understanding of stocks, bonds, and ETFs?") # 移除错误的Risk_Profile赋值语句 class Questionnine(forms.Form): # Risk CAPCITY choice = ((0, "1 to 4 years"), (5, "5 to 9 years"),(20,"10 to 19 years"),(35,"Over 19 years")) question9 = forms.TypedChoiceField(choices= choice, coerce=int, widget= forms.RadioSelect, label="How long do you plan to keep this investment?") def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # 如需自定义初始化逻辑,在此添加,不要覆盖默认参数
步骤2:修正views.py代码
- 补充模型导入语句
- 在
done方法中从表单实例提取用户选择的分数 - 计算总分数并保存到数据库
- 在HttpResponse中输出分数信息
完整的views.py代码:
from django.shortcuts import render from formtools.wizard.views import SessionWizardView from .forms import Signup, Questionone, Questiontwo, Questionthree, Questionfour, Questionfive, Questionsix, Questionseven,Questioneight,Questionnine from django.http import HttpResponse from .models import User, Risk_Profile class FormWizardView(SessionWizardView): # 可根据需求添加更多问卷表单到form_list form_list = [Signup, Questiontwo] template_name='index.html' def done(self, form_list, **kwargs): # 提取各表单的数据 signup_form = form_list[0] question_two_form = form_list[1] # 保存用户信息到User模型 user = User.objects.create( name=signup_form.cleaned_data['name'], last_name=signup_form.cleaned_data['last_name'], phone=signup_form.cleaned_data['phone'], email=signup_form.cleaned_data['email'] ) # 提取分数并计算 score_risk_toler = question_two_form.cleaned_data['question2'] # 后续可添加其他问题的分数提取,比如question1、question3等 score_risk_capc = 0 # 示例值,需根据实际问卷问题补充计算逻辑 total_score = score_risk_toler + score_risk_capc # 保存风险评分到Risk_Profile模型 Risk_Profile.objects.create( score_risk_toler=score_risk_toler, score_risk_capc=score_risk_capc, total_score=total_score, dude=user ) # 在HttpResponse中输出分数 return HttpResponse(f""" 提交成功!<br> 风险承受能力分数:{score_risk_toler}<br> 风险承受能力上限分数:{score_risk_capc}<br> 总分数:{total_score} """)
后续扩展说明
- 如需添加更多问卷问题,只需将对应的表单类添加到
form_list中,然后在done方法中依次提取cleaned_data中的字段值进行分数计算。 - 可根据实际需求调整分数计算逻辑,比如不同问题对应不同的权重或分类(风险承受/风险能力)。
内容的提问来源于stack exchange,提问作者Noor Negm
相关产品推荐
相关产品推荐

