【问题标题】:How to fix UnboundLocalError in Django website如何修复 Django 网站中的 UnboundLocalError
【发布时间】:2021-04-05 00:32:47
【问题描述】:

我收到此错误,“分配前引用了局部变量 'stu_details'”。请问怎么解决。

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('/')

【问题讨论】:

    标签: python django django-views django-templates


    【解决方案1】:

    看起来您的变量 context3 应该是包含每个学生信息的数组。你在循环之后声明了 context3,但是循环中存在 stu_details 和其他变量。

    我知道您需要这样的东西。

       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)
    

    希望我能正确理解您的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-24
      • 2021-04-07
      • 2014-02-24
      • 1970-01-01
      • 2021-12-11
      • 2013-08-15
      相关资源
      最近更新 更多