我的表单字段没有出现在html文件中

时间:2019-04-17 17:51:51

标签: python html django

我正在尝试解决此问题...我使用Forms.py创建了一个简单的发布表单,但是它没有显示在HTML文件中。我在Google上搜索过,但仍然不知道如何解决

views.py



from django.shortcuts import render
from contact.forms import contactForm

def contact(request):
    form = contactForm(request.POST)
    if form.is_valid():
        return request.POST
    context = locals()
    template = 'contact.html'
    return render(request, 'contact/contact.html')

contact.html


{% block content %}
<h1>
    Contact doesn't appears..
</h1>
<form method = "POST">{% csrf_token %}
    {{ form.as_p }}
<input type = "submit" value = "submit form" class = 'btn btn-default' />
</form>
{% endblock %}

forms.py

from django import forms
from django.shortcuts import render

class contactForm(forms.Form):
    name = forms.CharField(required = False, max_length = 100, help_text='100 characters max.')
    email = forms.EmailField(required = True)
    comment = forms.CharField(required = True, widget = forms.Textarea)

1 个答案:

答案 0 :(得分:0)

您需要在render函数中传递所需的对象。

def contact(request):
    ...
    context = {'form': form}
    return render(request, 'news/year_archive.html', context)

如您所见,您正在传递标记为context的词典到渲染器中,现在您的模板应该可以使用它了。

Django view example