3

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

视图.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,})

表格.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()

没有这个,表格效果很好。但是这条线是必须的。查询集必须动态更新。如何才能做到这一点?

4

1 回答 1

0

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

此代码必须有效:

if request.method == "POST":
    form = UploadFileForm(request.POST, request.FILES, tenant=this_tenant)
于 2017-03-09T12:41:05.407 回答