来自联系表单错误的电子邮件:不允许的方法(POST)405

时间:2019-04-24 20:17:32

标签: python html django

我正在我的投资组合网站上创建一个“联系人”页面,当用户填写并提交该页面时,它将自动将其作为电子邮件发送到我的个人电子邮件帐户。但是,当我单击“提交”时,终端中显示“不允许的方法(POST):/ contact /”,浏览器中显示“ HTTP错误405”,帐户中没有电子邮件。

我的HTML:

 <form action="" method="POST">

  {% csrf_token %}

  <div class="row form-group">
    <div class="col">
      <input name="f-name" type="text" class="form-control" placeholder="First name" required>
    </div>
    <div class="col">
      <input name="s-name" type="text" class="form-control" placeholder="Last name" required>
    </div>
  </div>

  <div class="form-group">
    <input name="email" type="email" class="form-control" id="email-input" aria-describedby="emailHelp" placeholder="name@mail.com" required>
    <small id="emailHelp" class="form-text text-muted">I Wont Share Your Email!</small>
  </div>

  <div class="form-group text-center">
    <textarea name="e-message" class="form-control" id="exampleFormControlTextarea1" rows="3" placeholder="your message..." required></textarea>
  </div>

  <button type="submit" class="btn btn-primary">Send</button>

</form>

我的views.py:

class ContactView(TemplateView):
     template_name = 'contact.html'

     def send_message(self, request):
        if request.method == 'POST':
            message = request.POST['f-name', 's-name', 'email', 'e-message']
            send_mail('Contact Form', message,['email@gmail.com'],
            fail_silently=False)

            return render(request, 'thanks.html')

我的项目urls.py

 from django.contrib import admin
 from django.urls import path, include
 from django.contrib.auth import views
 from blog import views

 urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('blog.urls')),
    path('projects/', views.ProjectView.as_view(), name='projects'),
    path('blog/', views.BlogView.as_view(), name='blog'),
    path('contact/', views.ContactView.as_view(), name='contact'),
    path('thanks/', views.ThanksView.as_view(), name='thanks'),

我的应用程序urls.py

from django.conf.urls import url
from blog import views


app_name = 'blog'

urlpatterns = [
    url(r'^$', views.AboutView.as_view(), name='about'),
    url(r'^projects/$', views.ProjectView.as_view(), name='projects'),
    url(r'^blog/$', views.BlogView.as_view(), name='blog'),
    url(r'^contact/$', views.ContactView.as_view(), name='contact'),
    url(r'^thanks/$', views.ThanksView.as_view(), name='thanks'),

我一直在寻找类似答案的几个小时,到目前为止到目前为止,还没有任何类似的帮助?也许我应该在Django表单中重建表单?我不想冒险进行太多更改并破坏我的网站!

1 个答案:

答案 0 :(得分:0)

Django不隐式支持模板视图上的post方法。您必须像这样在模板视图中自行定义发布方法

class ContactView(TemplateView):
     template_name = 'contact.html'

     def post(self, request, *args, **kwargs):
        message = request.POST['e-message']
        send_mail('Contact Form', message,['email@gmail.com'], fail_silently=False)

        return render(request, 'thanks.html')

其余的将自动处理