我正在尝试在 django 上做一个 matplotlib 条形图。将使用的数据将从我的数据库中查询。
我在运行代码时遇到了这个错误:
分配前引用的 /graph.png 局部变量“主题”处的 UnboundLocalError
matplotlib 部分的代码都是正确的,因为我之前尝试运行静态数据并且它有效。但是,当我尝试从数据库中查询数据时,会在 views.py 上导致此错误。我之前在不同的页面上做过很多次这个查询并且工作正常。但这不适用于此请求。为什么?
def bar_chart(request):
#Topic Distribution
topics = list(topic.objects.filter(subject_id=subj_id).order_by('id').values())
fig = Figure()
ax = fig.add_subplot(111)
N = 5
ind = np.arange(N)
width = 0.35
group_labels = [] #list of x-axis tick labels
y = [] #list of y-values
total_marks = 0 #total marks
for topic in topics:
t_questions = question.objects.filter(topic_id=topic.id)
if (len(t_questions) != 0):
topic_marks = 0 #each topic starts at 0 marks distribution
for t_question in topic_questions:
topic_marks += t_question.marks #accumulate the marks
total_marks += topic_marks
y.append(topic_marks)
group_labels.append(topic.title)
for yval in y:
yval = yval/total_marks * 100 #convert to percentage
ax.bar(ind, y, width, color='r')
ax.set_ylabel('Distribution in %')
ax.set_title('Topic Distribution')
ax.set_xticks(ind)
ax.set_xticklabels(group_labels)
fig.autofmt_xdate()
canvas=FigureCanvas(fig)
response=HttpResponse(content_type='image/png')
canvas.print_png(response)
return response