[Python] If you suddenly want to create an inquiry form

Nice to meet you. This is Taro Man. I usually develop web services.

-** Siltrend **

Introduction

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 **.

Overall picture

This article uses ** Django **. Django is very useful.

本文を追加.png

Form definition

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.

Sample code
#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.")

Process definition

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.

Sample code
#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

Screen definition

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.

Inquiry screen

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>
Screen after sending an inquiry

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>

URL definition

Define ** URL and process association ** in ʻurls.py`.

Sample code
#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'),
]

Email information definition

Finally, settings.py defines the ** email information ** used by the program. Specify the SMTP server, port number, and user information.

Sample code
EMAIL_HOST = 'smtp.XXX.com'
EMAIL_PORT = XXX
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'XXX'
EMAIL_USE_TLS = True

Summary

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

[Python] If you suddenly want to create an inquiry form
If you want to create a Word Cloud.
Don't write Python if you want to speed it up with Python
I want to know if you install Python on Mac ・ Iroha
If you want to assign csv export to a variable in python
What to do if you couldn't send an email to Yahoo with Python.
If you want to include awsebcli with CircleCI, specify the python version
Python Note: When you want to know the attributes of an object
[Python] If you want to draw a scatter plot of multiple clusters
If you want to count words in Python, it's convenient to use Counter.
I want to create a window in Python
How to build an environment when you want to use python2.7 after installing Anaconda3
If you want to make a TODO application (distributed) now using only Python
What to do if you get an error when installing python with pyenv
If you want to make a discord bot with python, let's use a framework
[Blender x Python] How to create an original object
If you want to use Cython, also include python-dev
How to create an image uploader in Bottle (Python)
What to do if you get an OpenSSL error when installing Python 2 with pyenv
What to do if you get an error when importing matplotlib in Python (Mac)
What to do if you run python in IntelliJ and end with an error
A convenient function memo to use when you want to enter the debugger if an error occurs when running a Python script.
Solution when you want to use cv_bridge with python3 (virtualenv)
[Django] A memorandum when you want to communicate asynchronously [Python3]
I want to initialize if the value is empty (python)
[Python] How to write an if statement in one sentence.
If you want your colleagues to use the same language
An introduction to Python Programming
[Python Kivy] How to create an exe file with pyinstaller
If you want to put an argument in the closure function and execute it later
If you want to use field names with hyphens when updating firestore data in python
When you want to hit a UNIX command on Python
[Django] Memo to create an environment of Django + MySQL + Vue.js [Python]
[Python] If you create a file with the same name as the module to be imported, an Attribute Error will occur.
[Django] What to do if the model you want to create has a large number of fields
What to do if you get an error saying c compiler cannot create executables in configure
[Subprocess] When you want to execute another Python program in Python code
Do you want to wait for general purpose in Python Selenium?
If you want to become a data scientist, start with Kaggle
What to do if you can't install pyaudio with pip #Python
What to do if you get a minus zero in Python
How to create a heatmap with an arbitrary domain in Python
[Python] When you want to use all variables in another file
Indispensable if you use Python! How to use Numpy to speed up operations!
When you want to send an object with requests using flask
[TensorFlow] If you want to run TensorBoard, install it with pip
Check if you can connect to a TCP port in Python
Various ways to create an array of numbers from 1 to 10 in Python.
[For Python] Quickly create an upload file to AWS Lambda Layer
Create folders from '01' to '12' with python
Nice to meet you with python
Create an Excel file with Python3
How to create an email user
Create python directory Support if directory exists
Key operations you want to know
5 Ways to Create a Python Chatbot
I want to debug with Python
An introduction to Python for non-engineers
An alternative to `pause` in Python
[Python] Create API to send Gmail
[Python Tutorial] An Easy Introduction to Python