Advanced search
Evgenij LegotskojOct. 15, 2016, 9:50 a.m.

DjangoDjango - 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',
    ...
]

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 .

Timeweb

Let me recommend you the excellent hosting on which EVILEG is located.

For many years, Timeweb has been proving his stability.

For projects on Django I recommend VDS hosting

View Hosting
s

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

  • Result:42points,
  • Rating points-8
e
  • enfant
  • Oct. 14, 2021, 2:59 p.m.

C++ - Test 002. Constants

  • Result:75points,
  • Rating points2
e
  • enfant
  • Oct. 14, 2021, 2:54 p.m.

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

  • Result:93points,
  • Rating points8
Popular publications in the last 90 Days
Last comments
s

Qt/C++ - Lesson 060. Configuring the appearance of the application in runtime

Добрый вечер, на "лету" не работает, только перезапуск
s

Qt/C++ - Lesson 060. Configuring the appearance of the application in runtime

Спасибо, завтра опробую и отпишусь по результату

Django - Tutorial 007. Adding Pagination based on django-bootstrap3

Просто список каких-нибудь объектов передавайте, который дёрнули ищ api стороннего сервера from django.core.paginator import Paginatorobjects = ['john', 'paul', 'george', 'ringo']p = Pagina…
b

PyQt5 - Tutorial 009. Using QThread with MoveToThread

Спасибо большое

PyQt5 - Tutorial 009. Using QThread with MoveToThread

Вызвать либо метод quit() либо эквивалентный его вариант - метод exit(0)
Now discuss on the forum
  • Nomad
  • Oct. 15, 2021, 6:39 a.m.

Вопрос из раздела "как реализовать"

Всем привет. Есть бизнес логика которую надо реализовать на джанге, она состоит в следующем: надо реализовать функционал регистрации/авторизации компаний у которого есть свой дашборд …

Проблема с созданием файлов перевода для составного проекта

Я имею ввиду, если у вас был старые ts файлы, то написать парсер, который составил бы словарь переводов. Например. "Hello world" - "Привет мир" "Hello dev" - "Привет dev" и…
k

QPsql Компиляция драйвера

при компиляции драйвера из окна Qt 5.15.2 (MSVC2019 64 ) надо было запустить C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Auxiliary\Build\vcvars64.bat тогда компиляция вып…
P
  • Pisych
  • Oct. 12, 2021, 10:59 p.m.

Фильтр в Select формы Django

Добрый день! Подскажите, как можно сделать? Есть форма, связанная с моделью. В форме Select, выбор типа документа (Приход, Расход,Списание). Этот Select берет данные из таблицы типов документов.…

Вызов функции Python с Qml

Чтобы onResult в QML подключилось к чему-то в Python, нужно чтобы result было сигналом, а у вас это слот. В качестве сигнала определено takeFunc и в данном случае в QML должно ра…
About
Services
© EVILEG 2015-2021
Recommend hosting TIMEWEB