gpt4 book ai didi

python - django 表单未在模板中呈现。输入字段不显示

转载 作者:太空宇宙 更新时间:2023-11-03 15:50:40 25 4
gpt4 key购买 nike

我无法在模板中看到 django 表单。它没有被正确渲染。我已经尝试过解决这个问题,但表格没有显示。在一个新项目中尝试了相同的代码来测试,效果很好,但在这里不起作用。这个 {{ form.as_p }} 没有显示任何内容,即没有输入字段供我输入详细信息并检查其他部分。提前致谢。

# forms.py

class ContactForm(forms.Form):
contact_name = forms.CharField(required=True)
contact_email = forms.EmailField(required=True)
contact_subject = forms.CharField(required=True)
content = forms.CharField(
required=True,
widget=forms.Textarea
)`

和:

# views.py

def contact(request):
form_class = ContactForm


if request.method == 'POST':
form = form_class(data=request.POST)

if form.is_valid():
contact_name = request.POST.get(
'contact_name'
, '')
contact_email = request.POST.get(
'contact_email'
, '')
contact_subject = request.POST.get(
'contact_subject'
, '')
form_content = request.POST.get('content', '')

# Email the profile with the
# contact information
template = get_template('contact_template.txt')
context = Context({
'contact_name': contact_name,
'contact_email': contact_email,
'contact_subject' : contact_subject,
'form_content': form_content,
})
content = template.render(context)

email = EmailMessage(
"New contact form submission",
content,
"Your website" +'',
['youremail@gmail.com'],
headers = {'Reply-To': contact_email }
)
email.send()
return redirect('contact')

return render(request, 'contact.html', {
'form': form_class,
})

相同的模板如下所示。

模板

 <section id="contact">
<div class="container text-center">
<div class="row text-center">
<div class="bg-image">
<div class="col-md-6 col-md-offset-3 text-center share-text wow animated zoomInDown heading-text">
<p class="heading">
If you got any questions, please do not hesitate to send us a message.
</p>
</div>
</div>
</div>

{% block content %}
<h1>Contact</h1>
<form role="form" action="" method="post">{% csrf_token %}

{{ form.as_p }}

<button type="submit">Submit</button>
</form>
{% endblock %}
</div>
</section>

最佳答案

添加 else 子句以在 GET 上生成表单:

def contact(request):

form_class = ContactForm

if request.method == 'POST':
form = form_class(data=request.POST)
# ... more code from above ...
else:
form = form_class() # this is important

return render(request, 'contact.html', {
'form': form, # NOTE: instead of form_class!!!!
})

关于python - django 表单未在模板中呈现。输入字段不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41328586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com