Django - Tutorial 013. Contact form based on Django

контактная форма, 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',
    ...
]

Naturally 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'

    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 :: Message via contact form '
            email_body = "From site message was sended\n\n" \
                         "Sender name: %s \n" \
                         "E-mail: %s \n\n" \
                         "Message: \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>Welcome to site</p>
        <p>If you have any requests or suggestions to improve the site, or you want to suggest an article for publication on the website, you can do so by using the contact form:</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;Send</button>
            {% endbuttons %}
        </form>
    {% else %}
        <p>Message sended</p>
    {% endif %}
    </article>
{% endblock %}

The result of this code you can see on the contact page of this website.

For Django I recommend VDS-server of 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.
Support the author Donate
DR

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

B

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

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

Comments

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

Hello, Dear Users of EVILEG!!!

If the site helped you, then support the development of the site financially, please.

You can do it by following ways:

Thank you, Evgenii Legotckoi

p
Feb. 17, 2020, 2:41 p.m.
pstMem

C++ - Тест 003. Условия и циклы

  • Result:85points,
  • Rating points6
z
Feb. 17, 2020, 6:02 a.m.
zet

C++ - Test 006. Enumerations

  • Result:80points,
  • Rating points4
z
Feb. 17, 2020, 5:49 a.m.
zet

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

  • Result:80points,
  • Rating points4
Last comments
Feb. 17, 2020, 3:22 a.m.
Evgenij Legotskoj

Добрый день. Это кастомный тег, помещается в файл, который находится в каталоге templatetags myapp/ templatetags/ myapp.py
B
Feb. 16, 2020, 1:36 p.m.
BahaMeirman

Добрый вечер! Монжно по подробней о теге get_companion? ссылка не работает.
Feb. 16, 2020, 9:35 a.m.
Evgenij Legotskoj

Добрый день. На GitHub исходники, можете посмотреть в официальном репозитории
B
Feb. 16, 2020, 9:29 a.m.
BahaMeirman

Здравстсвуйте Евгений, непонятно мне где эти исходники найти?
Now discuss on the forum
IP
Feb. 20, 2020, 1:24 a.m.
Igor' Poroshin

QSqlQuery query("SELECT CONCAT("#", LPAD(HEX(`t`.RGB), 6, 0)) FROM table AS t");query.exec(); while (query.next()) { QColor(query.value(0).toString()); }
IP
Feb. 19, 2020, 11:55 p.m.
Igor' Poroshin

qDebug() << model->lastError().text() - возвращает текст и код ошибки, который возвращает база данных, чаще всего ошибка бывает из-за неправильного SQL запроса qDebug() << mo…
Feb. 19, 2020, 8:55 a.m.
Mihailll

Можно через сервер сделать
V
Feb. 19, 2020, 7:09 a.m.
Vitali

Да, прямо сходу не заработало, а сейчас просто некогда разбираться, да и я уже решил не использовать в этом приложении WebEngine. Ошибка: WebEngineContext used before QtWebEngine::initialize(…
Feb. 19, 2020, 7:01 a.m.
BlinCT

Просто реально не вижу тут каких то проблем в модели, вот вообще ничего. Но она все равно не отображается, то есть ладно бы если данные бы не появлялись а сама таблица была бы. Так и таблиц…
EVILEG
About
Services
© EVILEG 2015-2019
Recommend hosting TIMEWEB