1
我沒有得到如何記住值並在表單驗證中顯示錯誤。Django - 如何記住值並在表單驗證中顯示錯誤?
這裏是我的代碼:
template.html:
<form method="post" action="/submeter/anuncio/">{% csrf_token %}
{{form_main.as_p}}
{{form_bicyclead.as_p}}
{{form_bicycleadcategory.as_p}}
{{form_bicycleaditemkindandpropertyvalueform.as_p}}
<input type="hidden" name="section" value="5" />
<input type="submit">
</form>
views.py:
def submit_ad_view(request):
if request.method == 'POST':
model_main = Main()
model_main.section = Section.objects.get(pk=request.POST['section'])
model_main.user = request.user
model_bicyclead = BicycleAd()
model_bicyclead.bicycleadtype = BicycleAdType.objects.get(pk=2)
model_bicyclead.bicycleaditemkind = BicycleAdItemKind.objects.get(pk=4)
model_bicyclead.bicycleadcondition = BicycleAdCondition.objects.get(pk=2)
model_bicyclead.city = GeonamesLocal.objects.get(pk=4803854)
form_main = MainForm(request.POST, instance = model_main)
form_bicyclead = BicycleAdForm(request.POST, instance = model_bicyclead)
form_bicycleadcategory = BicycleAdCategoryForm(request.POST)
if form_main.is_valid() and form_bicyclead.is_valid() and form_bicycleadcategory.is_valid():
main_f = form_main.save()
bicyclead_f = form_bicyclead.save(commit=False)
bicyclead_f.main = main_f
bicyclead_f.save()
bicycleadcategory_f = form_bicycleadcategory.save(commit=False, rel_obj=model_bicyclead)
resultado = 'valid'
else:
resultado = 'n_valid'
return render_to_response('app_p/submit_ad.html', {'form_main': form_main, 'form_bicyclead': form_bicyclead, 'form_bicycleadcategory': form_bicycleadcategory, 'form_bicycleaditemkindandpropertyvalueform': form_bicycleaditemkindandpropertyvalueform}, context_instance=RequestContext(request))
else:
form_main = MainForm()
form_bicyclead = BicycleAdForm()
form_bicycleadcategory = BicycleAdCategoryForm()
form_bicycleaditemkindandpropertyvalueform = BicycleAdItemKindAndPropertyValueForm()
return render_to_response('app_p/submit_ad.html', {'form_main': form_main, 'form_bicyclead': form_bicyclead, 'form_bicycleadcategory': form_bicycleadcategory, 'form_bicycleaditemkindandpropertyvalueform': form_bicycleaditemkindandpropertyvalueform}, context_instance=RequestContext(request))
對什麼是錯在這個模板中的某些線索,並以沒有得到錯誤並且不記得表單的值?
最好的問候,
我更新了代碼。我可以將哪些變量傳遞給表單? –
你是否獲得與更新的代碼相同的結果? –
嗨。是的,結果是一樣的。沒有錯誤,也沒有數據重新填充。 –