首页 > 解决方案 > 在提交 Django ChoiceField 表单时,仅返回表单集中的第一个字典

问题描述

我已经按以下顺序定义了一个具有 2 个表单的表单集。

  1. 类型编号(学生证)
  2. 输入文本(课程名称)

视图.py

for form in formset:
    if form.has_changed():
        print(form.cleaned_data)

提交 post 请求时 formset.cleaned_data 返回

[{'student_id': 1, 'course_name': 'English'}, {'student_id': 2, 'course_name': 'Math'}, {'student_id': 3, 'course_name': 'PE'}]

我还添加了一个检查 form.has_changed(),所以如果我提交 'History' 而不是 'English' 其中 id 等于 1 我的 form.cleaned_data 会返回预期的字典。

{'student_id': 1, 'course_name': 'History'}

我的问题:

当我有一个“course_name”的类型文本表单时,一切都按预期工作。当我将文本表单更改为单选时,我只遇到了一个问题,因此表单集如下:

  1. 类型编号(学生证)
  2. 类型 ChoiceField(课程名称)

formset.cleaned_data 返回相同的字典列表。

[{'student_id': 1, 'course_name': 'English'}, {'student_id': 2, 'course_name': 'Math'}, {'student_id': 3, 'course_name': 'PE'}]

但是,如果我提交“历史”以更改 id 等于 3 的“PE”课程,form.cleaned_data 总是返回列表中的第一个字典。

{'student_id': 1, 'course_name': 'English'}

为什么会这样?在表单集中使用 ChoiceField 有什么问题吗?

当我更改为单选时,表单变量似乎没有正确循环表单集,因为它只返回列表中的第一个字典。

[编辑]

视图.PY

def generate_student_info(request):

    # Retrieve inputted value
    current_student_id = request.POST.get('student_id')
    current_course_name = request.POST.get('course_name')

    # Read the table from the database
    connection = db.open_connection(read_only=False)
    sql_str = f"""SELECT * FROM {students_table};"""
    df = db.read(sql_statement=sql_str, connection=connection)

    # creating a formset
    insert_formset = formset_factory(StudentInfoForm, extra=0)
    formset = insert_formset(request.POST or None, initial=[{'student_id': df['student_id'][i], 'course_name': df['course_name'][i]} for i in range(len(df))])

    if request.method == 'POST':
        if formset.is_valid():
             for form in formset:
                 if form.has_changed():
                    print(form.cleaned_data)
                    try:
                        #some MySQL code to be executed
        else:
            print('formset is not valid')

    context = {'formset': formset}

    return render(request, 'student_info_table.html', context)

表格.PY

class StudentInfoForm(forms.Form):

    student_id = forms.IntegerField(label='student_id', required=False, min_value=0)

    # course_name= forms.ChoiceField(
    #     choices=[(student_info_df['course_name'][i], student_info_df['course_name'][i]) for i in
    #              range(len(student_info_df))],
    #     label="")

    course_name= forms.CharField(label='course_name', required=False)

标签: pythondjangodjango-viewsdjango-forms

解决方案


推荐阅读