我是Django 1.9的新手,我正在编写一个网站。我正在尝试联系表单以进入联系页面。我使用了以下代码 - 它位于名为email.html的文件中:
{% extends 'blog/base.html' %}
<form method="post">
{% csrf_token %}
{{ form }}
<div class="form-actions">
<button type="submit">Send</button>
</div>
</form>
我在view.py文件中定义了它:
from .forms import PostForm, ContactForm
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
def email(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
try:
send_mail(subject, message, from_email, ['nmam.ltd@gmail.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('thanks')
return render(request, "blog/email.html", {'form': form})
def thanks(request):
return HttpResponse('Thank you for your message.')
.....
以及forms.py文件:
from django import forms
class ContactForm(forms.Form):
from_email = forms.EmailField(required=True)
subject = forms.CharField(required=True)
message = forms.CharField(widget=forms.Textarea)
另外,在urls.py文件中:
from django.conf.urls import patterns, url
from . import views
urlpatterns = [
url(r'^general.html/$', views.general, name='general'),
url(r'^dcmain.html/$', views.dcmain, name='dcmain'),
url(r'^dcmain.html/big_data.html/$', views.big_data, name='big_data'),
url(r'^dcmain.html/Data_Architecture.html/$', views.Data_Architecture, name='Data_Architecture'),
url(r'^dcmain.html/BI_MI.html/$', views.BI_MI, name='BI_MI'),
url(r'^dcmain.html/Master_Data.html/$', views.Master_Data, name='Master_Data'),
url(r'^dcmain.html/Data_Q.html/$', views.Data_Q, name='Data_Q'),
url(r'^dcmain.html/Project_M.html/$', views.Project_M, name='Project_M'),
url(r'^email.html/$', views.email, name='email'),
url(r'^thanks/$', views.thanks, name='thanks'),
]
当我将email.html文件链接到主页并点击该链接时,即使网址显示我在email.html页面上显示主页(如下所示),它也会显示主页:
我对Django编程完全不熟悉。我试过研究它,但我找不到解决方案。请有人帮助我。
答案 0 :(得分:0)
您的网址很可能是问题所在。您可以阅读有关Django网址here的更多信息。
请注意,正如Django文档所述,将使用与请求的URL匹配的第一个URL模式。作为一个基本的经验法则,我建议您在空白网址模式之前添加更具体的网址格式。例如:
urlpatterns = [
url(r'^email.html/$', views.email, name='email'),
url(r'^thanks/$', views.thanks, name='thanks'),
url(r'^$', views.index, name='some_name'),
]
如果从项目urls.py文件中包含此urls.py文件,您将希望在根网址模式之前包含这些网址。
urlpatterns = [
url(r'^blog/', include('blog.urls', namespace='blog'),
url(r'', views.site_home, name='site_home'),
]
然后将您的网址设为此页面
<a href="{% url 'blog:email' %}">Email</a>
将呈现为
<a href="yoursite.com/blog/email.html">Email</a>