Django上传表单,导致错误的其他字段
问题描述:
存在我正面临的问题。我需要上传包含相关数据的学生的Excel。作为用户输入,我还需要有一批学生。以下是我的代码:Django上传表单,导致错误的其他字段
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()
没有这一点,形式的伟大工程。但是这条线是必须的。查询集必须动态更新。如何才能做到这一点?
答
当您保存表单时,您必须传递租户参数,否则其查询集将为空,您的选择将不会被选中。
此代码必须工作:
if request.method == "POST":
form = UploadFileForm(request.POST, request.FILES, tenant=this_tenant)
哇,通过化险为夷。谢谢Amin! – Sayantan