Django上传表单,附加字段导致错误

时间:2017-03-09 06:47:43

标签: python django upload django-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 :(得分:0)

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

此代码必须有效:

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