coderboy
coderboy

Reputation: 759

How to fix UnboundLocalError in Django website

I am getting this error, "local variable 'stu_details' referenced before assignment". How can i fix it please.

views.py

def assignment_page(request):
    if request.method == "POST":
        get_course_name = request.POST.get('get_course_name')
        add_courses_get = add_courses.objects.get(Course_Name=get_course_name)
        stu_course_all_stu = add_courses.objects.filter(Course_Name=add_courses_get)

        for all_stu_details in stu_course_all_stu:
            for stu_details in all_stu_details.student.all():
                id_ = stu_details.student_ID
                name = stu_details.student_name
       context3 = {"stu_details":stu_details, "id_":id_, "name": name, 'stu_course_all_stu':stu_course_all_stu}

        return render(request, 'assignment_page.html', context3)

    else:
        return redirect('/')

Upvotes: 0

Views: 69

Answers (1)

Viktor Shvachuk
Viktor Shvachuk

Reputation: 71

It's look like your variable context3 should be array with information about every students. You declare context3 after loop, but stu_details and other variables exist in the loop.

I understand that you need something like this.

   context3 = []
   for all_stu_details in stu_course_all_stu:
        for stu_details in all_stu_details.student.all():
            id_ = stu_details.student_ID
            name = stu_details.student_name
            context3.append({"stu_details":stu_details, "id_":id_, "name": name, 'stu_course_all_stu':stu_course_all_stu})

    context = {'context3': context3}
    return render(request, 'assignment_page.html', context)

I hope I understand your problem right.

Upvotes: 1

Related Questions