Nice to meet you. This is Taro Man. I usually develop web services.
-** Siltrend **
The other day, I suddenly wanted to prepare a ** inquiry form **, In addition, I wanted to send the content to my ** email address **, so Implemented in ** Python **.
This article uses ** Django **. Django is very useful.

Form definition is done in forms.py.
Basically, it's created by importing ** Django standard features **.
In addition, define ** form items **. It's like "name", "contact information", "inquiry content". You can also define mandatory settings and character restrictions for each item.
#Import Django standard features
from django import forms
from django.core.mail import BadHeaderError, send_mail
from django.http import HttpResponse
#Import Django settings
from django.conf import settings
class ContactForm(forms.Form):
    #As a form item"name"Define
    name = forms.CharField(
        label='',
        max_length=100,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': "name",
        }),
    )
    #As a form item"mail address"Define
    email = forms.EmailField(
        label='',
        widget=forms.EmailInput(attrs={
            'class': 'form-control',
            'placeholder': "mail address",
        }),
    )
    #As a form item"Content of inquiry"Define
    message = forms.CharField(
        label='',
        widget=forms.Textarea(attrs={
            'class': 'form-control',
            'placeholder': "Content of inquiry",
        }),
    )
    #send an email
    def send_email(self):
        subject = "Contact Us"
        message = self.cleaned_data['message']
        name = self.cleaned_data['name']
        email = self.cleaned_data['email']
        from_email = '{name} <{email}>'.format(name=name, email=email)
        #Specify recipient list
        recipient_list = [settings.EMAIL_HOST_USER]
        try:
            send_mail(subject, message, from_email, recipient_list)
        except BadHeaderError:
            return HttpResponse("An invalid header has been detected.")
The process is defined in views.py.
This is also created by importing ** Django standard features **.
In addition, import the above form definition. Also, specify the HTML ** to be displayed and the URL ** to be transitioned.
#Import Django standard features
from django.urls import reverse_lazy
from django.views.generic import TemplateView
from django.views.generic.edit import FormView
# forms.Import form definition from py
from .forms import ContactForm
#Define the behavior of the submit event
class ContactFormView(FormView):
    #Specify the html to be displayed
    template_name = 'contact_form.html'
    # form.Specify the class name defined in py
    form_class = ContactForm
    #Specify the url after transition as an argument
    success_url = reverse_lazy('contact_result')
    #Send email
    def form_valid(self, form):
        form.send_email()
        return super().form_valid(form)
#Define behavior after submitting a form
class ContactResultView(TemplateView):
    #Specify the html to be displayed
    template_name = 'contact_result.html'
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['success'] = "The inquiry was sent successfully."
        return context
Prepare an inquiry screen and a screen after sending the inquiry.
On the inquiry screen, use {{form.as_p}} to
Renders the items defined in the form definition with the <p> tag.
contact_form.html
<h4>Contact Us</h4>
  <div>
    <p><br>Please enter the required information.</p>
    <form method="POST">{% csrf_token %}
      {{ form.as_p }}
      <button type="submit" class="btn">Send</button>
      <a href="{% url 'top' %}">Back to top</a>
    </form>
  </div>
</div>
contact_result.html
<div>
  <p>
Inquiry transmission completed
  </p>
  <div>
    <p>
Thank you for your inquiry.<br>
We will reply after confirming the contents.
    </p>
    <a href="{% url 'top' %}">Back to top</a>
  </div>
</div>
Define ** URL and process association ** in ʻurls.py`.
#Import processing class
# <PROJECT_NAME>Is your project name
from <PROJECT_NAME>.views import ContactFormView, ContactResultView
urlpatterns = [
    # ...
    path('contact/', ContactFormView.as_view(), name='contact_form'),
    path('result/', ContactResultView.as_view(), name='contact_result'),
]
Finally, settings.py defines the ** email information ** used by the program.
Specify the SMTP server, port number, and user information.
EMAIL_HOST = 'smtp.XXX.com'
EMAIL_PORT = XXX
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'XXX'
EMAIL_USE_TLS = True
By using Django standard features, I was able to easily create an inquiry form. I hope it will be helpful when you want to create an inquiry form.
Recommended Posts