• Skip to main content
  • Skip to primary sidebar

学習記録

Djangoでコンタクトフォームの作成

2021年6月10日 by 河副 太智 Leave a Comment

Djangoでコンタクトフォームの作成を行う際
Koji Mochizuki様の記事を参考にさせて頂きました。
リンクができないのでURLを以下に貼っておきます。
https://medium.com/@kjmczk/django-contact-form-5a35d43b00a6

しかし、そのままではエラーが出てしまうため修正を行い、
SendGridを活用したSMTP送信の方法を備忘録として記録しておく。

SendGridの登録方法はLearnDjango様のページ下部Email Serviceを参考

Contents

  • 1 forms.py
  • 2 view.py
  • 3 urls.py
  • 4 テンプレートの作成
    • 4.1 contact_form.html
    • 4.2 contact_result.html
  • 5 settings.py

forms.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
from django import forms
from django.conf import settings
from django.core.mail import BadHeaderError, send_mail
from django.http import HttpResponse
 
class ContactForm(forms.Form):
    name = forms.CharField(
        label='',
        max_length=100,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': "お名前",
        }),
    )
    email = forms.EmailField(
        label='',
        widget=forms.EmailInput(attrs={
            'class': 'form-control',
            'placeholder': "メールアドレス",
        }),
    )
    message = forms.CharField(
        label='',
        widget=forms.Textarea(attrs={
            'class': 'form-control',
            'placeholder': "お問い合わせ内容",
        }),
    )
 
    def send_email(self):
        subject = "お問い合わせ"
        message = self.cleaned_data['message']
        name = self.cleaned_data['name']
        email = self.cleaned_data['email']
        from_email = 'xxxxxx@xxxxxx.com'
        admin_email = ['xxxxxx@xxxxxx.com']
 
        #メッセージと名前とメールを結合
        send_message = message + "\n" + name + "\n" + email
        try:
            send_mail(subject ,send_message, from_email, admin_email)
        except BadHeaderError:
            return HttpResponse("無効なヘッダが検出されました。")

from_emailとadmin_emailに代入するメールアドレスはそれぞれSendGridのSingle Sender VerificationにあるFROMとREPLYと一致させないとエラーになってしまう。

その為、コンタクトフォームから連絡をもらってもfromが自分のアドレスなので
そのまま直接返信ができないという奇妙な状態にあり、これは未解決。

また、admin_emailの部分はリストかタプルでないと受け付けてもらえない、
送信先アドレスをSendGridのSingle Sender Verificationにある

 

SendGridにSender設定したメールアドレスの確認はSingleSenderVerificationを確認。

Settings > Sender Authentication > Single Sender Verification > Veryfy a Single Senderでも
行ける。

view.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from django.views.generic import TemplateView
from django.views.generic.edit import FormView
from .forms import ContactForm
 
class ContactFormView(FormView):
    template_name = 'contact/contact_form.html'
    form_class = ContactForm
    success_url = 'result'
 
    def form_valid(self, form):
        form.send_email()
        return super().form_valid(form)
 
 
class ContactResultView(TemplateView):
    template_name = 'contact/contact_result.html'
 
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['success'] = "お問い合わせは正常に送信されました。"
        return context

urls.py

1
2
3
4
5
6
7
8
from django.urls import path,include
from .views import ContactFormView, ContactResultView
 
urlpatterns = [
    ...
    path('contact/', ContactFormView.as_view(), name='contact_form'),
    path('contact/result/', ContactResultView.as_view(), name='contact_result'),  
]

テンプレートの作成

プロジェクトルートのtemplates内にcontactフォルダを作り、その中にcontact_form.html、contact_result.htmlファイルを新規作成

1
2
3
4
templates/
    contact/
        contact_form.html
        contact_result.html

contact_form.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{% block content %}
<div class="container">
  <div class="row">
    <div class="col-md-8">
      <h1>お問い合わせ</h1>
      <p>お問い合わせフォームです。</p>
      <form method="POST">{% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="btn btn-primary">送信</button>
      </form>
    </div>
  </div>
</div>
{% endblock %}

contact_result.html

1
2
3
{% block content %}
{{ success }}
{% endblock %}

settings.py

1
2
3
4
5
6
7
8
9
10
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
ACCOUNT_EMAIL_VERIFICATION = "none"
 
# sendgrid でメール送信する場合
DEFAULT_FROM_EMAIL = 'xxxxx@xxxxxx.com'
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey' #ここは本当にapikeyと入力する個別の名称ではない
EMAIL_HOST_PASSWORD = 'SG.j2Ixxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
EMAIL_PORT = 587
EMAIL_USE_TLS = Trueこ

これでcontact/ページにいけばフォームが設置されており、送信が可能。

このエントリーをはてなブックマークに追加

Tweet
[`yahoo` not found]
このエントリーを Google ブックマーク に追加
LinkedIn にシェア
LINEで送る


Filed Under: Django

Reader Interactions

コメントを残す コメントをキャンセル

メールアドレスが公開されることはありません。 ※ が付いている欄は必須項目です

Primary Sidebar

カテゴリー

  • AWS
  • Bootstrap
  • Dash
  • Django
  • flask
  • GIT(sourcetree)
  • Plotly/Dash
  • VPS
  • その他tool
  • ブログ
  • プログラミング
    • Bokeh
    • css
    • HoloViews
    • Jupyter
    • Numpy
    • Pandas
    • PosgreSQL
    • Python 基本
    • python3
      • webアプリ
    • python3解説
    • scikit-learn
    • scipy
    • vps
    • Wordpress
    • グラフ
    • コマンド
    • スクレイピング
    • チートシート
    • データクレンジング
    • ブロックチェーン
    • 作成実績
    • 時系列分析
    • 機械学習
      • 分析手法
      • 教師有り
    • 異常値検知
    • 自然言語処理
  • 一太郎
  • 数学
    • sympy
      • 対数関数(log)
      • 累乗根(n乗根)
    • 暗号学

Copyright © 2025 · Genesis Sample on Genesis Framework · WordPress · Log in