我可以使用Django(2.1)成功创建联系表单。
在HTML模板的{% csrf_token %}
内的{% block content %}{% endblock %}
内放置表单标签时,无法使“成功”页面“触发”。
为什么使用jinja
标签会发生这种情况?
中间件:
'django.middleware.csrf.CsrfViewMiddleware',
urls.py
from django.conf.urls import url, include
from django.urls import path
from . import views
# from django.contrib.auth.views import login
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^$', views.about, name='about'),
url(r'^$', views.howitworks, name='services'),
url(r'^$', views.showroom, name='showroom'),
url(r'^privacy/', views.privacy, name='privacy'),
url(r'^terms-of-service/', views.tos, name='terms-of-service'),
url(r'^contact/', views.emailView, name='contact'),
# path('email/', views.emailView, name='email'),
path('success/', views.successView, name='success'),
]
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.core.mail import send_mail, BadHeaderError
from .forms import ContactForm
def index(request):
return render(request, 'home/landing.html')
def about(request):
return render(request, 'home/landing#about.html')
def howitworks(request):
return render(request, 'home/landing#services.html')
def showroom(request):
return render(request, 'home/landing#portfolio.html')
def privacy(request):
return render(request, 'home/privacy.html')
def tos(request):
return render(request, 'home/terms-of-service.html')
# def contact(request):
# return render(request, 'home/contact.html')
# def login(request):
# return render(request, 'auth/account/login.html')
# def signup(request):
# return render(request, 'auth/account/signup.html')4
def emailView(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
subject = form.cleaned_data['subject']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
try:
send_mail(subject, message, from_email, ['peterdoh@gmail.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('success')
return render(request, "home/contact.html", {'form': form})
def successView(request):
# return HttpResponse('Success! Thank you for your message to Revs Direct.')
return render(request, "home/success.html", {})
contact.html
{% extends "home/base.html" %}
{% load staticfiles %}
{% block header %}
{% include 'home/header1.html' %}
{% endblock %}
{% block content %}
<h3 class="section-title">Contact Us</h3>
<p class="section-description">We d love to hear from you. Please fill in the form below with any queries or questions that
you may have.</p>
<div class="container wow fadeInUp">
<div class="row justify-content-center">
<div class="col-lg-3 col-md-4">
<div class="info">
<!-- <div>
<i class="fa fa-map-marker"></i>
<p>A108 Adam Street<br>New York, NY 535022</p>
</div> -->
<!-- <div>
<i class="fa fa-envelope"></i>
<p>info@revsdirect.com</p>
</div> -->
<!-- <div>
<i class="fa fa-phone"></i>
<p>HOLD</p>
</div> -->
</div>
<div class="social-links">
<h3>Social Media</h3>
<a href="#" class="facebook">
<i class="fab fa-facebook-f"></i>
</a>
<a href="#" class="instagram">
<i class="fab fa-instagram"></i>
</a>
<a href="#" class="twitter">
<i class="fab fa-twitter"></i>
</a>
<!-- <a href="#" class="google-plus"><i class="fa fa-google-plus"></i></a>
<a href="#" class="linkedin"><i class="fa fa-linkedin"></i></a> -->
</div>
</div>
<div class="col-lg-5 col-md-8">
<div class="form">
<!-- <div id="sendmessage">Your message has been sent. Thank you!</div>
<div id="errormessage"></div> -->
<form role="form" action="" method="post" class="contactForm">{% csrf_token %}
{{ form.as_p }}
<div class="form-actions">
<button type="submit">Send</button>
</div>
</form>
</div>
</div>
</div>
{% endblock %}
答案 0 :(得分:0)
您保存表格了吗?
if form.is_avlid():
myform = form.save(commit=False)
# add as per your requirement
myform.save()
return statement
答案 1 :(得分:0)
我在https://hellowebbooks.com/news/tutorial-setting-up-a-contact-form-with-django/的指导下找到了可行的解决方案。
在contact.html中,我使用了:
<div class="container">
<br>
<br>
<h2>Contact</h2>
<p>Send me a message</p>
{% if messages %}
<div class="row">
<div class="col-xs-12">
{% for message in messages %}
<p {% if message.tags %} class="{{ message.tags }}" {% endif %}>{{ message }}</p>
{% endfor %}
</div>
</div>
{% endif %}
<form role="form" action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<button class="button primary type=" submit">Send Message</button>
</form>
</div>
然后在我的表格中。py:
from django import forms
class ContactForm(forms.Form):
contact_name = forms.CharField(required=True)
contact_email = forms.EmailField(required=True)
content = forms.CharField(
required=True,
widget=forms.Textarea(attrs={'rows': 4, 'cols': 40})
)
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.fields['contact_name'].label = "Your name:"
self.fields['contact_email'].label = "Your email:"
self.fields['content'].label = "Your message:"
最后是我的views.py:
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from .forms import ContactForm
from django.contrib import messages
from django.core.mail import EmailMessage
from django.template.loader import get_template
# Create your views here.
def index(request):
form_class = ContactForm
# new logic!
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', '')
form_content = request.POST.get('content', '')
# Email the profile with the
# contact information
template = get_template('landing/contact_template.txt')
context = {
'contact_name': contact_name,
'contact_email': contact_email,
'form_content': form_content,
}
content = template.render(context)
email = EmailMessage(
"[Peter Doherty] New contact form submission",
content,
"Peter Doherty" +'',
['peterdoh@gmail.com'],
headers = {'Reply-To': contact_email }
)
email.send()
messages.success(request, 'Thank you. Message sent.')
# return redirect('^$')
return render(request, 'landing/index.html', {'form': form_class,})
目前尚不清楚为什么第一种方法会引发错误。这种方法行之有效,并且已经通过了测试。此外,请确保settings.py文件中的电子邮件配置正确。