Django 上传表单,附加字段导致错误
Django upload form, additional field causing error
我遇到了一个问题。我需要上传包含相关数据的 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>
如果我删除批处理字段,该表单将运行良好。谁能帮我解决这个问题?
post 总是得到第一个选项,即:
<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)
我遇到了一个问题。我需要上传包含相关数据的 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>
如果我删除批处理字段,该表单将运行良好。谁能帮我解决这个问题?
post 总是得到第一个选项,即:
<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)