B
B
blazer052017-01-12 16:52:40
Django
blazer05, 2017-01-12 16:52:40

Error with csrf token?

Hello.
I can't open the contact form.
Access Error (403)
CSRF validation failed. Request denied.
On another site, a similar form works fine.

from django.conf.urls import url
from django.contrib import admin
from index.views import index
from contactform.views import contactform, thanks

urlpatterns = [
    url(r'^$', index, name='index'),
    url(r'^$', contactform, name='contactform'),
    url(r'^thanks/', thanks, name='thanks'),
    url(r'^admin/', admin.site.urls),
]

from django.core.mail import BadHeaderError, send_mail
from django.http import HttpResponse, HttpResponseRedirect, request
from django.shortcuts import render, render_to_response
from django.template import RequestContext
from django.template.context_processors import csrf

from contactform.forms import ContactForm
from contactform.models import MailBox



# Функция формы обратной связи

def contactform(reguest):
    if reguest.method == 'POST':

        form = ContactForm(reguest.POST)
        # Если форма заполнена корректно, сохраняем все введённые пользователем значения
        if form.is_valid():
            subject = form.cleaned_data['subject']
            sender = form.cleaned_data['sender']
            phone = form.cleaned_data['phone']
            diament = form.cleaned_data['diament']
            adress = form.cleaned_data['adress']
            copy = form.cleaned_data['copy']

            recepients = ['[email protected]']

            # Положим копию письма в базу данных
            MailBox.objects.create(subject=subject, sender=sender, phone=phone, diament=diament, adress=adress, copy=copy)

            # Если пользователь захотел получить копию себе, добавляем его в список получателей
            if copy:
                recepients.append(sender)
            try:
                send_mail(subject, adress, '[email protected]', recepients)
            except BadHeaderError: #Защита от уязвимости
                return HttpResponse('Invalid header found')
            # Переходим на другую страницу, если сообщение отправлено
            return HttpResponseRedirect('/thanks/')

    else:
        form = ContactForm()
    # Выводим форму в шаблон
    return render(request, 'contact.html', {'form': form})

In template
<form class="s_form" action="{% url 'contactform' %}" method="post">
     {% csrf_token %}
 <input class="s_text nameinp sinp" name="subject" placeholder="ФИО  для заказа" type="text">

 <input style="background: rgb(255, 255, 255) url({% static 'odrova/img/background/input-maill11.png' %}) no-repeat scroll 3% center; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;"
 class="s_text nameinp" name="diament" placeholder="Диаметр вашего вала" type="text">

 <input name="email" class="email" value="[email protected]u" type="hidden">

 <input style="background: rgb(255, 255, 255) url({% static 'odrova/img/background/input-maill.png' %}) no-repeat scroll 3% center; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;"
 class="s_text nameinp" name="sender" placeholder=" Ваш Email" type="text">

 <input style="background: rgb(255, 255, 255) url({% static 'odrova/img/background/input-maill1.png' %}) no-repeat scroll 3% center; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;"
 class="s_text nameinp" name="adress" placeholder="Адрес отправки посылки" type="text">

 <input style="background: rgb(255, 255, 255) url({% static 'odrova/img/background/input-tel.png' %}) no-repeat scroll 3% center; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;"
 class="s_text nameinp" name="phone" placeholder="Ваш телефон" type="text">

 <input class="s_submit" onclick='return yaCounter30038354.reachGoal("TARGETT"),!0' value="Отправить заказ." type="button">

 </form>

forms.py
from django.forms import ModelForm
from contactform.models import MailBox

class ContactForm(ModelForm):
    class Meta:
        model = MailBox
        fields = ['subject', 'sender', 'phone', 'diament', 'adress', 'copy']

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Tyrion Lannister, 2017-01-16
@baYonet_cpp

At the end of the views line
try like this:

args = {}
args.update(csrf(request))
args['form'] = form
return render(request, 'contact.html', args)

S
Snewer, 2017-07-05
@BadassRolf

It needs to be split into two separate queries:

mysqli_query($connection,"INSERT INTO `ents` SELECT * FROM `clients` WHERE id='". $_POST['id'] ."'");
mysqli_query($connection,"DELETE FROM `clients` WHERE id='". $_POST['id2'] ."'");

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question