[英]Django Form not rendering in template
I must just be overlooking something here, but after stripping everything back - I can't seem to get Django to render either a Form or ModelForm to my template. 我必须在这里忽略一些东西,但是将所有内容剥离一遍之后-我似乎无法让Django将Form或ModelForm渲染到我的模板中。 Code below: 代码如下:
#forms.py
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField()
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)
#views.py
def index(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid(): # All validation rules pass
return HttpResponseRedirect('/thanks/')
else:
form = ContactForm() # An unbound form
return render_to_response('home/new_website.html',{
'form': form,
})
#new_website_html
<html>
<body>
<form method = "post" action = "">
{{ form.as_p }}
</form>
</body>
</html>
I had the same issue and after many tries this is my solution: 我遇到了同样的问题,经过多次尝试,这是我的解决方案:
Change the view from this 从这里改变看法
#views.py
else:
form = ContactForm() # An unbound form
return render_to_response('home/new_website.html',{
'form': form,
})
To that: 对此:
#views.py
else:
form = ContactForm() # An unbound form
return render_to_response('home/new_website.html',{
'form': form,
})
Or a simple newline is enough: 或简单的换行符就足够了:
#views.py
else:
form = ContactForm() # An unbound form
return render_to_response('home/new_website.html',{
'form': form,
})
Strange thing is, after these changes the original code worked. 奇怪的是,这些更改之后,原始代码起作用了。
Any error page or just blank page? 任何错误页面还是空白页面? Actually I just try your code and get form rendering correct(I don't know how to insert local result image here) Please make sure DEBUG=TRUE in settings.py while it's not the problem. 实际上,我只是尝试您的代码并获得正确的表单呈现(我不知道如何在此处插入本地结果图像)请确保在settings.py中DEBUG = TRUE,但这不是问题。 @Burhan I think indent problem only happens because he edits it in stackoverflow. @Burhan我认为缩进问题仅会发生,因为他在stackoverflow中对其进行了编辑。 Btw, your form doesn't have a submit button, maybe add it in html like 顺便说一句,您的表单没有提交按钮,也许像html一样添加它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.