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 .

Virtual hosting with 10 percent discount
Virtual hosting with 10 percent discount
EVILEG offers reliable hosting with a 10% discount for virtual hosting and 5% for VPS
Support the author Donate
DR

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

Comments

Only authorized users can post comments.
Please, Log in or Sign up
MB
July 14, 2019, 5:57 p.m.
Maksim Belikov

C++ - Test 005. Structures and Classes

  • Result:100points,
  • Rating points10
MB
July 14, 2019, 5:52 p.m.
Maksim Belikov

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:90points,
  • Rating points8
MB
July 14, 2019, 5:45 p.m.
Maksim Belikov

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

  • Result:71points,
  • Rating points1
Last comments
July 16, 2019, 3:15 p.m.
Evgenij Legotskoj

Конечно )) На самом деле не все читали Шлее... я например не читал ))
July 16, 2019, 3:05 p.m.
IscanderChe

Так пример с QLocalServer и QLocalSocket я целиком переписал с QTcpSocket и QTcpServer из книги Шлее. Принципиальное отличие - где коннект ставить. :)) Разве что на это упор сделать. Но я могу...
July 16, 2019, 2:47 p.m.
Evgenij Legotskoj

Лучше API ))) Кстати, по использованию QLocalServer и QLocalSocket на сайте нет статей, было бы очень полезно и хорошо пошло бы в раздел Qt.
July 16, 2019, 12:36 p.m.
IscanderChe

Да, прямой доступ не предполагается. Впрочем, можно, конечно, и напрямую. Всё равно всё локально происходит. Проблема в том, как донести сведения об изменениях в базе, которые вносит клиент, д...
b
July 16, 2019, 8:38 a.m.
bbb116

спасибо, до smart pointer еще не дошел )
Now discuss on the forum
July 17, 2019, 11:49 a.m.
Mihailll

В настройкак указан индификатор проекта и ключ. Осталось понять как использовать ключ. Попробовал вставить в этот запрос 'https://[PROJECT_ID].firebaseio/users/jack/name.json?access_to...
b
July 17, 2019, 9:01 a.m.
bbb116

Вообщем работает только если делать setSceneRect только в конструкторе главного окна, если потом менять rect например при вставке картинки то появляются сколлы все как надо только области не р...
July 17, 2019, 5:54 a.m.
Aleksej Vnukov

хочу не стандартный набор символов, а все ненужное убрать чтоб не мешало. для начала решил посмотреть как работает клава на родном примере, а он на телефоне не взлетел вот и начал разби...
July 17, 2019, 5:06 a.m.
Mihailll

Добрый день.Возможно вы сталкивались с облаками.Нужно из Qt создавать на облаке папки, записывать в папки файлы, читать и удалять с компьютера файлы.Возможно знаете, что лучше и проще испол...
Looking for a Job?
25,000.00 руб. - 30,000.00 руб.
Разработчик Qt/C++
Barnaul, Altai Krai, Russia

For registered users on the site there is a minimum amount of advertising

EVILEG
About
Services
Join us
© EVILEG 2015-2019
Recommend hosting TIMEWEB