我正在django中创建一个联系表单来发送电子邮件,但表单没有显示在网页上。我认为问题可能是因为表单对象可能从未正确传递给上下文,但我不知道它出错的地方。下面的代码是我到目前为止的代码。
from .forms import *
我的观点
def email(request):
form = ContactForm()
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
email = form.cleaned_data['email']
first_name = form.cleaned_data['first_name']
message = form.cleaned_data['message']
try:
send_mail(first_name + ": " + subject, message, email,
['flavioandersites@gmail.com'])
except BadHeaderError:
return HttpResponse("Invalid Header.")
return redirect('thankyou')
return render(request, 'Index-App/contact.html', {'form': form})
我的表单类
class ContactForm(forms.Form):
subject = forms.CharField(required=True)
from_email = forms.EmailField(required=True)
first_name = forms.CharField(max_length=200, required=True)
message = forms.CharField(widget=forms.Textarea)
网址
url(r'^contact/$', views.email, name='contact'),
我的模板
{% block contact %}
<form method="POST" action="{% url 'Index-App:contact' %}">
{% csrf_token %}
{{ form }}
<input type="submit" class="btn-success" value="Send"/>
</form>
{% endblock %}
答案 0 :(得分:4)
因为当方法为GET
时,您没有实例化表单。此外,您需要将self
参数更改为request
尝试以下方法:
def email(request): # pass request for your view param, not self
form = ContactForm() # You should instantiate your form for GET method
if request.method == 'POST':
form = ContactForm(request.POST)
# ...
return render(request, 'Index-App/contact.html', {'form': form})