I am trying to do a matplotlib bar chart on django. The data that will be used, will be queried from my database.
I came across this error when I run my code:
UnboundLocalError at /graph.png local variable ‘topic’ referenced
before assignment
The code for matplotlib part are all correct as I tried running static data before and it worked. However, when I tried quering data from database, it causes this error on views.py. I have done this query many times before on different pages and working fine. But it doesn’t work for this request. Why?
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
The error is here:
If you are following the common naming conventions for models, yours is probably called Topic, so it should be
Otherwise you are likely missing an import.
It’s caused by the local variable topic defined within the function and overshadowing the global one.