Django上传表单,额外的字段导致错误

3

我面临一个问题。我需要上传一个包含学生相关数据的 Excel 文件。同时,我还需要作为用户输入学生所在的批次。以下是我的代码:

Views.py

def import_student(request):
    this_tenant=request.user.tenant
    if request.method == "POST":
        form = UploadFileForm(request.POST, request.FILES)

        def choice_func(row):
            data=student_validate(row, this_tenant, batch_selected)
            return data

        if form.is_valid():
            data = form.cleaned_data
            batch_data= data['batch']
            batch_selected=Batch.objects.for_tenant(this_tenant).get(id=batch_data)

            with transaction.atomic():
                try:
                    request.FILES['file'].save_to_database(
                        model=Student,
                        initializer=choice_func,
                        mapdict=['first_name', 'last_name',     'dob','gender','blood_group', 'contact', 'email_id', \
                       'local_id','address_line_1','address_line_2','state','pincode','batch','key','tenant','user'])
                    return redirect('student:student_list')
                except:
                    transaction.rollback()
                    return HttpResponse("Error")
        else:
            print (form.errors)
            return HttpResponseBadRequest()
    else:
        form = UploadFileForm(tenant=this_tenant)

    return render(request,'upload_form.html',{'form': form,})

Forms.py

class UploadFileForm(forms.Form):
    file = forms.FileField()
    batch = forms.ModelChoiceField(Batch.objects.all())
    def __init__(self,*args,**kwargs):
        self.tenant=kwargs.pop('tenant',None)
        super (UploadFileForm,self ).__init__(*args,**kwargs) # populates the post
        self.fields['batch'].queryset =     Batch.objects.for_tenant(self.tenant).all()
        self.helper = FormHelper(self)
        self.helper.add_input(Submit('submit', 'Submit', css_class="btn-xs"))
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-sm-2'
        self.helper.field_class = 'col-sm-4'

然而,提交表单时显示的错误(我正在打印错误)是:
<ul class="errorlist"><li>batch<ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul></li></ul>

如果我删除批次字段,表单就可以正常工作。有人可以帮我吗?
文章总是得到第一个选项,即:
<option value="">---------</option>

其他具有不同值和名称(而不是-------)的选项未被选中。尽管如此,客户端实际上正在选择其他选项。
现在,我发现错误是由以下行引起的:
self.fields['batch'].queryset = Batch.objects.for_tenant(self.tenant).all()

没有这个,表单可以正常工作。但是这行代码是必须的。查询集必须动态更新。如何实现?

1个回答

0

在保存表单时,您必须传递租户参数,否则其查询集将为空,您的选择将无法被选中。

这段代码必须能够正常工作:

if request.method == "POST":
    form = UploadFileForm(request.POST, request.FILES, tenant=this_tenant)

哇,那救了我的一天。谢谢 Amin!! - Sayantan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接