Privacy policyContactsAbout siteOpinionsGitHubDonate
© EVILEG 2015-2018
Recommend hosting
TIMEWEB

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 .

Comments

Only authorized users can post comments.
Please, Log in or Sign up
v
Jan. 17, 2019, 11:51 a.m.
vitalir12

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

  • Result:20points,
  • Rating points-10
v
Jan. 17, 2019, 11:49 a.m.
vitalir12

C++ - Test 002. Constants

  • Result:50points,
  • Rating points-4
v
Jan. 17, 2019, 11:13 a.m.
vitalir12

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

  • Result:28points,
  • Rating points-10
Last comments
I
Jan. 16, 2019, 8:06 a.m.
IscanderChe

Заработало. Забыл model->select(); вписать.
I
Jan. 16, 2019, 8:02 a.m.
IscanderChe

Всё равно пусто, хотя строка с данными в базу добавляется.
Jan. 16, 2019, 7:51 a.m.
Евгений Легоцкой

потому, что нужно сохранять информацию для всех остальных ролей и столбцов через вызов переопределённого метода. Да к тому же вы ещё и зациклили вызов метода data. QVariant MySqlTableModel:...
I
Jan. 16, 2019, 7:43 a.m.
IscanderChe

Сделал вот так. В tableView ничего нет, кроме заголовка. QVariant MySqlTableModel::data(const QModelIndex &index, int role) const{ if (role == Qt::DisplayRole) { QTime ...
Now discuss on the forum
Jan. 18, 2019, 11:26 a.m.
nayk1982

Для Desktop делал так: void pause(int ms){ QTimer timer; timer.setInterval( qBound(1, ms, 3600000) ); timer.setSingleShot(true); QEventLoop loop; QObject::connect(&...
Jan. 17, 2019, 12:01 p.m.
Алексей Внуков

у меня просто есть отдельное поле с чекбоксамими какие колонки нужно отображать CheckBox { id: checkBox text: qsTr("some text") checked: true onC...
Jan. 15, 2019, 4:53 p.m.
Михаиллл

Спасибо, заработало.Но выдало обычный текст без форатирования HTML.Придется искать дальше
Jan. 15, 2019, 12:52 p.m.
BlinCT

Я же вам выше написал CLion умеет работать с ремоут машинами. И Qt так же собирает.
Join us in social networks

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