电子邮件表单不会显示在模板上

时间:2017-09-18 01:24:44

标签: python django

我正在开发一个网站,该网站会在我的数据库中显示一些数据,以及人们可以与我联系的表格。

views.py

from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from .forms import ContactForm
from django.utils import timezone
from .models import Logo, SkillLanguages, SkillAPI, SkillFrameworks, 
WorkPortfolio, PersonalPortfolio

def index(request):
logo=Logo.objects.all()
skill_languages=SkillLanguages.objects.all()
skill_api=SkillAPI.objects.all()
skill_frameworks=SkillFrameworks.objects.all()
work_portfolio=WorkPortfolio.objects.all()
personal_portfolio=PersonalPortfolio.objects.all()
return render(request, 'johann/index.html', {'logo': logo, 'skill_languages': skill_languages, 'skill_api': skill_api, 'skill_frameworks': skill_frameworks, 'work_portfolio': work_portfolio, 'personal_portfolio': personal_portfolio})


def email(request):
    if request.method == 'GET':
        form = ContactForm()
else:
        form = ContactForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            from_email = form.cleaned_data['from_email']
            message = form.cleaned_data['message']
            try:
                send_mail(name, message, from_email, ['myemail@notsuspiciousmailserver.com'])
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            return redirect('success')
    return render(request, "johann/index.html", {'form': form})


def success(request):
    return HttpResponse('<script>alert("Success! Thank you for your message."); window.location = "https://pqdrl7qd.apps.lair.io/#contact";</script>')

urls.py

from django.conf.urls import include, url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^$', views.email, name='email'),
    url(r'^success/$', views.success, name='success'),
]

我发现我的问题在于我对前两个网址做了什么,如果我切换了电子邮件URL和索引URL的位置,我的模板将显示我的表单而不是存储在我的模型中的数据,反之亦然。我该怎么办?

2 个答案:

答案 0 :(得分:0)

您有两个相同的网址模式

url(r'^$', views.index, name='index'),
url(r'^$', views.email, name='email'),

将按顺序评估它们,并且索引视图将始终首先匹配。找到匹配后,其他网址模式将被忽略。

您需要为电子邮件视图提供不同的路线。我可以建议

url(r'^email/$', views.email, name='email'),

答案 1 :(得分:0)

您可以使用:

url(r'^$', views.index, name='index'),
url(r'^email/$', views.email, name='email'),