我有一个视图及其模板,用于处理和打印表单。表单有一个ChoiceField,它将模型列表作为选项。这是我的观点,模板和表格:
*views.py*
def index(request):
form = dbForm()
print "form is: ", form
return render(request, 'Directories/index.html', {'form':form})
*index.html*
<div id="content" align="center">
<form action="" method="get"> {% csrf_token %}
{{form.as_p}}
<input type="submit" value="Edit" name="_add" />
</form>
*forms.py*
model_classes = []
class dbForm(forms.Form):
model_classes_field = forms.ChoiceField(choices=models())
def models():
apps = get_app('Directories')
for model in get_models(apps):
model_classes.append( (model._meta.verbose_name, model._meta.db_table), )
return model_classes
提交的模型选择被发送到另一个视图,其中ModelForm显示模型的字段并期望提交每个字段的数据。然后将提交的数据存储在数据库中,并将用户重定向回索引以从头开始。这是视图,模板和表单:
*views.py*
def modelUpdate(request):
if 'update' in request.POST: # If the form has been submitted...
form_class = get_dynamic_form(request.GET['model_classes_field'])
form = form_class(request.POST)
if form.is_valid(): # All validation rules pass
row = form.save() #saves into database
return render(request, 'Directories/index.html')
else:
print "form errors: ", form.errors
return HttpResponse('ERROR -- Return to form submission')
*create.html*
<form action="" method="post"> {% csrf_token %}
{% for f_name in field_names %}
{% if not forloop.first %}
{{f_name}}: <input id="edit-{{f_name}}" type="text" name={{f_name}} /><br />
{% endif %}
{% endfor %}<br />
<input type="submit" name="update" value="Update" />
<input type="reset" name="Clear" value="Clear" />
</form>
*forms.py*
#create a ModelForm using a dynamic model
def get_dynamic_form(c_model):
model_class = get_model('Directories', c_model)
class ObjForm(forms.ModelForm ):
class Meta:
model = model_class
return ObjForm
将数据保存到数据库后,将表单重定向回index.html return render(request, 'Directories/index.html')
时会出现问题。会发生什么是index.html根本不显示{{form.as_p}}
形式。虽然当我在我的服务器(Apache)error.log中检查print "form is: ", form
时,我的表单就会打印出来。
我无法理解为什么在重定向发生后数据不会在我的模板中呈现,但它们仍然在我的服务器日志中正确显示。
答案 0 :(得分:2)
您应该像form
视图一样将index
实例传递给模板。您的代码应更新为
def modelUpdate(request):
if 'update' in request.POST: # If the form has been submitted...
form_class = get_dynamic_form(request.GET['model_classes_field'])
form = form_class(request.POST)
if form.is_valid(): # All validation rules pass
row = form.save() #saves into database
#------------------------------------------------v pass it to template
return render(request, 'Directories/index.html', {'form': form})
else:
print "form errors: ", form.errors
return HttpResponse('ERROR -- Return to form submission')