Evgenii Legotckoi
Evgenii LegotckoiOct. 15, 2016, 9:50 a.m.

Django - Tutorial 013. Contact form based on Django

Continuing the development of the site, I would like to share an example of code for adding a contact form on the site to Django. There have already been articles with different shapes, for example, to add comments, but just talking about the entire process as a whole, and we will not get, and this theme party.

Especially that for a site on Wordpress for me it was a pain. Probably, all the fault was laziness, because I did not have any desire to begin to deal with PHP , to sketch out a contact form on their own (as a result of another plugin was used).

And when you consider that the development on the Django , quite often involves working with various forms of data, and thus there is a module for working with e-mail services, and the addition of such a form is not difficult.


Configuring settings.py, urls.py, home/urls.py

The first thing to do is to set up the configuration file, because it will be necessary to specify the data for connecting to the mailbox from which you will be sent a letter with the contents of the contact form.

EMAIL_HOST = 'smtp.example.com'          # Server for sending messages
EMAIL_HOST_USER = 'info@example.com'     # Username
EMAIL_HOST_PASSWORD = 'password123'      # Password
EMAIL_PORT = 2525                        # port of protocol
EMAIL_USE_TLS = True                     # using encoding
DEFAULT_FROM_EMAIL = 'info@example.com'  # email

Also, in this file you must specify the application that will be responsible for the contact form. In my case, this is the app home, which is responsible for rarely changing pages, such as a contact form. Also used on the site django-bootstrap3 module.

INSTALLED_APPS = [
    ...
    'home.apps.HomeConfig',
    'bootstrap3',
    ...
]

Of course mostly urls.py file Set the template on which the request is sent to the application.

urlpatterns = [
    url(r'^', include('home.urls')),
]

With regard to the url template for home application, it will be as follows:

from django.conf.urls import url

from . import views

app_name = 'home'
urlpatterns = [
    ...
    url(r'^contacts/$', views.EContactsView.as_view(), name='contacts'),
    ...
]

Contact form

The contact form is present three fields:

  1. Username - the user which must be presented;
  2. email - the user which must specify your e-mail, to be able to answer him;
  3. Message

All fields are mandatory. The check entry correctness email will be back in the user's browser.

Contact form code will be located in forms.py file.

# -*- coding: utf-8 -*-

from django import forms


class ContactForm(forms.Form):

    name = forms.CharField(
        label="Имя",
        widget=forms.TextInput
    )

    email = forms.EmailField(
        widget=forms.EmailInput
    )

    message = forms.CharField(
        label="Сообщение",
        widget=forms.Textarea
    )

View

Now write view, which will be responsible for processing the message and display a page with a contact form.

from django.shortcuts import render_to_response, reverse
from django.views import View
from django.core.mail import send_mail

from .forms import ContactForm
from project import settings


class EContactsView(View):
    template_name = 'home/contacts.html'

    # В случае get запроса, мы будем отправлять просто страницу с контактной формой
    def get(self, request, *args, **kwargs):
        context = {}
        context.update(csrf(request))    # Обязательно добавьте в шаблон защитный токен
        context['contact_form'] = ContactForm()

        return render_to_response(template_name=self.template_name, context=context)

    def post(self, request, *args, **kwargs):
        context = {}

        form = ContactForm(request.POST)

        # Если не выполнить проверку на правильность ввода данных,
        # то не сможем забрать эти данные из формы... хотя что здесь проверять?
        if form.is_valid():
            email_subject = 'EVILEG :: Сообщение через контактную форму '
            email_body = "С сайта отправлено новое сообщение\n\n" \
                         "Имя отправителя: %s \n" \
                         "E-mail отправителя: %s \n\n" \
                         "Сообщение: \n" \
                         "%s " % \
                         (form.cleaned_data['name'], form.cleaned_data['email'], form.cleaned_data['message'])

            # и отправляем сообщение
            send_mail(email_subject, email_body, settings.EMAIL_HOST_USER, ['target_email@example.com'], fail_silently=False)

        return render_to_response(template_name=self.template_name, context=context)

Here there is one key point concerning the display of the page to the user. If the user is sent a letter, it must inform you that the message was sent. To do this, we simply will not be placed in the context of a contact form in the template to check for its presence, to display the correct information to the user.

Template of contact form

The contact form is necessarily necessary to specify {% csrf_token%} , which will protect your site from attack via the contact form. And also do not forget to load bootsrtap3 module that will create a more correct and beautiful look of the page.

To use the contact form module bootstrap3 only need to specify the appropriate template tag and send our contact form to it. I draw your attention to the fact that depending on the availability of the contact form different appearance of the page will be displayed.

{% extends 'home/base.html' %}{% load bootstrap3 %}
{% block title %}Контакты{% endblock %}
{% block page %}
    <h1>Контакты</h1>
    <article>
    {% if contact_form %}
        <p>Добро пожаловать на сайт.</p>
        <p>Если у Вас есть пожелания или предложения по улучшению сайта, либо Вы желаете предложить статью к публикации на сайте, то Вы можете сделать это, воспользовавшись контактной формой:</p>
        <form id="contact_form" action="{% url 'home:contacts' %}" method="post">
            {% csrf_token %}
            {% bootstrap_form contact_form %}
            {% buttons %}
                <button type="submit" class="btn btn-primary">{% bootstrap_icon "send" %}&nbsp;&nbsp;Отправить</button>
            {% endbuttons %}
        </form>
    {% else %}
        <p>Сообщение отправлено</p>
    {% endif %}
    </article>
{% endblock %}

For Django I recommend VDS-server of Timeweb hoster Timeweb hoster .

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

DR
  • May 31, 2019, 11:12 a.m.
  • (edited)

Не полноценное решение, сильно вырвано из контекста.

B
  • Dec. 26, 2019, 1:08 a.m.

Здавствуйте! обязательно ли форма в django должна быть привязана к модели? конкретно в этом случаи

Evgenii Legotckoi
  • Jan. 6, 2020, 3:16 a.m.

Добрый день. Конкретно в этом случае модель не привязана к форме вообще потому, что здесь модель не используется. Вы можете использовать модель, чтобы дополнительно сохранять сообщения в базе данных сайта.

S
  • May 17, 2020, 6:37 a.m.

Добрый день,
не могу отправить загруженный файл, подскажите что нужно еще добавить.
Спасибо.

forms:
class ContactForm(forms.Form):

    name = forms.CharField(
        label="Имя",
        widget=forms.TextInput
    )

    email = forms.EmailField(
        widget=forms.EmailInput
    )

    message = forms.CharField(
        label="Сообщение", required=False,
        widget=forms.Textarea
    )
    file = forms.FileField(
        label="Загрузить файл", required=False,
    )

views:
class EContactsView(View):
    template_name = 'main/contacts.html'

    # В случае get запроса, мы будем отправлять просто страницу с контактной формой
    def get(self, request, *args, **kwargs):
        context = {}
        context['contact_form'] = ContactForm()
        return render(request, template_name=self.template_name, context=context)

    def post(self, request, *args, **kwargs):
        context = {}

        form = ContactForm(request.POST, request.FILES)

        # Если не выполнить проверку на правильность ввода данных,
        # то не сможем забрать эти данные из формы... хотя что здесь проверять?
        if form.is_valid():

            email_subject = ':: Сообщение через контактную форму '
            email_body = "С сайта отправлено новое сообщение\n\n" \
                         "Имя отправителя: %s \n" \
                         "E-mail отправителя: %s \n\n" \
                         "Сообщение: \n" \
                         "%s " % \
                         (form.cleaned_data['name'], form.cleaned_data['email'], form.cleaned_data['message'], form.cleaned_data['file'])


            # и отправляем сообщение

            send_mail(email_subject, email_body, settings.EMAIL_HOST_USER, ['mymail@gmail.com'], fail_silently=False)

        return render(request, template_name=self.template_name, context=context)

шаблон:

{% extends "layout/basic.html" %}
{% load thumbnail %}
{% load static %}
{% load bootstrap4 %}
{% block title %}Контакты{% endblock %}

{% block content %}
    <h1>Контакты</h1>
    <article>
    {% if contact_form %}
        <p>Добро пожаловать на сайт.</p>
        <p>Если у Вас есть пожелания или предложения по улучшению сайта, либо Вы желаете предложить статью к публикации на сайте, то Вы можете сделать это, воспользовавшись контактной формой:</p>
        <form id="contact_form" action="{% url 'main:contacts' %}" method="post" enctype="multipart/form-data">
            {% csrf_token %}
            {% bootstrap_form contact_form %}

            {% buttons %}
                <button type="submit" class="btn btn-success">&nbsp;&nbsp;Отправить</button>
            {% endbuttons %}
        </form>
    {% else %}
        <p>Сообщение отправлено</p>
    {% endif %}
    </article>
{% endblock %}
Evgenii Legotckoi
  • May 18, 2020, 3:20 a.m.

Добрый день.
Потому, что нужно не добавлять ссылку (или что там у вас в итоге получается) на файл и прикреплять его к письму.
Если не ошибаюсь, то для отправки письма с файлом нужно использовать класс EmailMessage

def send_email(request):
    ...
    email = EmailMessage(
        subject,
        content,
        contact_email,
        [to],
        headers={'Reply-To': contact_email}
    )
    if request.FILES:
        uploaded_file = request.FILES['file'] # file is the name value which you have provided in form for file field
        email.attach(uploaded_file.name, uploaded_file.read(), uploaded_file.content_type)
    email.send()

Могут быть некоторые разночтения в синтаксисе, в зависимости от версий Django

S
  • May 20, 2020, 7:08 a.m.

Добрый день, в итоге получилось как-то так, отправляет форму с файлом.
Спасибо.

settings:

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

views:

from django.core.mail import EmailMessage
from django.conf import settings

def contacts(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            email_subject = ' Сообщение через контактную форму '
            email_body = "С сайта отправлено новое сообщение\n\n" \
                         "Имя отправителя: %s \n" \
                         "E-mail отправителя: %s \n\n" \
                         "Сообщение: \n" \
                         "%s " % \
                         (form.cleaned_data['name'], form.cleaned_data['email'], form.cleaned_data['message'])

    email = EmailMessage(
        email_subject,
        email_body,
        settings.EMAIL_HOST_USER,
        ['mymail@gmail.com'],
    )
    if request.FILES:
        uploaded_file = request.FILES['file'] # file is the name value which you have provided in form for file field
        email.attach(uploaded_file.name, uploaded_file.read(), uploaded_file.content_type)
    email.fail_silently=False

    email.send()
    return render(request, 'main/contacts.html')
S
  • May 22, 2020, 7:52 a.m.

Добрый день,
при отправки письма с файлом, выбираю несколько файлов, пишет выбранное количество файлов, а отправляет только один, весь код см.выше, добавил только в форму возможность выбора нескольких файлов. Подскажите,что нужно еще добавить, чтобы можно было отправить сразу несколько файлов.
Спасибо.

class ContactForm(forms.Form):
file = forms.FileField(
        label="Загрузить файл", required=False,
        widget = forms.FileInput(attrs={'multiple': True})

    )
Evgenii Legotckoi
  • May 22, 2020, 7:57 a.m.

Думаю, что как-то так, возможно неправильно написание имени метода getlist, но выглядеть должно так

if request.FILES:
    for f in request.FILES.getlist('file'):
        email.attach(f.name, f.read(), f.content_type)
S
  • May 22, 2020, 11:10 a.m.

Спасибо, Евгений.
Все заработало.

def contacts(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            email_subject = ' Сообщение через контактную форму '
            email_body = "С сайта отправлено новое сообщение\n\n" \
                         "Имя отправителя: %s \n" \
                         "E-mail отправителя: %s \n\n" \
                         "Сообщение: \n" \
                         "%s " % \
                         (form.cleaned_data['name'], form.cleaned_data['email'], form.cleaned_data['message'])

        email = EmailMessage(
            email_subject,
            email_body,
            settings.EMAIL_HOST_USER,
            ['mymail@gmail.com'],
            )
        if request.FILES:
            for f in request.FILES.getlist('file'):
                email.attach(f.name, f.read(), f.content_type)
        email.fail_silently=False
        email.send()
    return render(request, 'main/contacts.html')
d
  • Feb. 16, 2023, 11:15 a.m.

Timeweb так себе провайдер.
Поддержка не отвечает. И smtp не отправляет письма.
Все перепробовал ничего найти не могу.
1. Ошибка sock.connect(sa) TimeoutError: [Errno 110] Connection timed out
2. Ошибка OSError: [Errno 101] Network is unreachable

Comments

Only authorized users can post comments.
Please, Log in or Sign up
B

C++ - Test 002. Constants

  • Result:16points,
  • Rating points-10
B

C++ - Test 001. The first program and data types

  • Result:46points,
  • Rating points-6
FL

C++ - Test 006. Enumerations

  • Result:80points,
  • Rating points4
Last comments
k
kmssrFeb. 9, 2024, 5:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 9:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 7:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 8:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
AC
Alexandru CodreanuJan. 19, 2024, 10:57 p.m.
QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…
BlinCT
BlinCTDec. 27, 2023, 7:57 p.m.
Растягивать Image на парент по высоте Ну и само собою дял включения scrollbar надо чтобы был Flickable. Так что выходит как то так Flickable{ id: root anchors.fill: parent clip: true property url linkFile p…
Дмитрий
ДмитрийJan. 10, 2024, 3:18 p.m.
Qt Creator загружает всю оперативную память Проблема решена. Удалось разобраться с помощью утилиты strace. Запустил ее: strace ./qtcreator Начал выводиться весь лог работы креатора. В один момент он начал считывать фай…
Evgenii Legotckoi
Evgenii LegotckoiDec. 12, 2023, 5:48 p.m.
Побуквенное сравнение двух строк Добрый день. Там случайно не высылается этот сигнал textChanged ещё и при форматировани текста? Если решиать в лоб, то можно просто отключать сигнал/слотовое соединение внутри слота и …

Follow us in social networks