我的django项目遇到此错误。我的应用程序称为“分数提交”
基本上我在网站上有一个功能,允许用户下载报告。
因此,在我的views.py文件中,我具有报告功能并导入report.py文件,其中显示了报告的生成方式
它显示了以下代码行中发生的错误:
submission=Submission.objects.get(month=month,year=reportyear,program=program)
Views.py
def report(request):
from scoresubmission.report import reportA, reportB, reportC
reportType = request.POST["reportType"]
reportYear = int(request.POST["reportYear"])
if reportType == 'a':
report_content = reportA(reportYear)
response = HttpResponse(report_content, content_type="text/csv")
response['Content-Disposition'] = 'inline; filename=5SAuditYearlySummaryReport_%d.xlsx' %reportYear
report.py,其中包含相关代码 用于设施中的设施: worksheet.write(row,col,facility.name,facility_format)
for i in range(12): # 12 months
month=i+1
programs=Program.objects.filter(facility_id=facility.id)
avg_totalscore=0
count=1
for program in programs:
print(program)
try:
submission=Submission.objects.get(month=month,year=reportyear,program=program)
print(submission)
avg_score=Result.objects.filter(submission=submission).aggregate(Avg('NewScore'))
#print avg_score.get('NewScore__avg')
avg_totalscore=(avg_totalscore + avg_score.get('NewScore__avg'))/count
count=count+1
except submission.DoesNotExist:
pass
#print avg_totalscore
if avg_totalscore!=0:
worksheet.write(row,i+3,avg_totalscore,red_format)
else:
worksheet.write(row,i+3,'-',red_format)
回溯(最近通话最近): 文件“ C:\ Users \ CHLOZHAO \ AppData \ Local \ Programs \ Python \ Python37 \ lib \ site-packages \ django \ core \ handlers \ exception.py”,第34行,位于内部 响应= get_response(请求) 文件“ C:\ Users \ CHLOZHAO \ AppData \ Local \ Programs \ Python \ Python37 \ lib \ site-packages \ django \ core \ handlers \ base.py”,行115,_get_response 响应= self.process_exception_by_middleware(e,请求) 文件“ C:\ Users \ CHLOZHAO \ AppData \ Local \ Programs \ Python \ Python37 \ lib \ site-packages \ django \ core \ handlers \ base.py”,行_get_response中的113 响应= wraped_callback(请求,* callback_args,** callback_kwargs) _wrapped_view中的文件“ C:\ Users \ CHLOZHAO \ AppData \ Local \ Programs \ Python \ Python37 \ lib \ site-packages \ django \ contrib \ auth \ decorators.py”,第21行 返回view_func(request,* args,** kwargs) 报告中的文件“ C:\ D Drive \ 5S Audit Website \ my5saudit \ scoresubmission \ views.py”,行185 report_content = reportA(reportYear) 在reportA中的文件“ C:\ D Drive \ 5S Audit Website \ my5saudit \ scoresubmission \ report.py”,行79 除了submit.DoesNotExist: UnboundLocalError:分配前已引用本地变量“提交”
答案 0 :(得分:0)
在您的except
中,您需要引用 class Submission
, not 对象,因为它本身不是 当时存在:
try:
submission=Submission.objects.get(month=month,year=reportyear,program=program)
print(submission)
avg_score=Result.objects.filter(submission=submission).aggregate(Avg('NewScore'))
#print avg_score.get('NewScore__avg')
avg_totalscore=(avg_totalscore + avg_score.get('NewScore__avg'))/count
count=count+1
except Submission.DoesNotExist: # reference to the class, not the object
pass
如果Sibmission.objects.get(..)
失败,则不会分配submission
变量,因此submission.DoesNotExist
毫无意义。
您应该从不使用该对象,并始终使用模型类本身来引用DoesNotExist
异常类。