I am creating a contact form in django to send an email but the form is not displaying on the webpage. I think the issue may be because the form object may have never been passed to the context correctly, but I have no idea where it is going wrong. The code below is what I have so far.
from .forms import *
My Views
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})
My Form Class
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)
Urls
url(r'^contact/$', views.email, name='contact'),
My Template
{% block contact %}
<form method="POST" action="{% url 'Index-App:contact' %}">
{% csrf_token %}
{{ form }}
<input type="submit" class="btn-success" value="Send"/>
</form>
{% endblock %}
Because you are not instantiating your form when method is GET
. Also, you need to change self
param to request
Try the following:
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})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.