Django - 403 Forbidden CSRF verification failed

2024/9/16 23:10:23

I have a contact form in Django for my website and when I was testing it locally it was working fine but now when I try to submit my contact form "live" it always comes up with 403 Forbidden CSRF verification failed.

view:

def contact(request):if request.method == 'POST':form = ContactForm(request.POST)if form.is_valid():cd = form.cleaned_datasend_mail(cd['subject'],cd['message'],cd.get('email', '[email protected]'),['[email protected]'],)return HttpResponseRedirect('/thanks/')else:form = ContactForm()return render(request, 'contact/contact.html', {'form': form})

contact.html

{% extends 'site_base.html' %}{% block head_title %}Contact{% endblock %}{% block body %}<h2>Contact Us</h2><p>To send us a message, fill out the below form.</p>{% if form.errors %}<p style="color: red;">Please correct the error{{ form.errors|pluralize }} below.</p>{% endif %}<form action="" method="POST">{% csrf_token %}<table>{{ form.as_table }}</table><br /><button type="submit" value="Submit" class="btn btn-primary">Submit</button></form>    {% endblock %}

settings (the ones I thought would be relevant):

SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
MIDDLEWARE_CLASSES = ["django.middleware.csrf.CsrfViewMiddleware","django.middleware.common.CommonMiddleware","django.contrib.sessions.middleware.SessionMiddleware","django.contrib.auth.middleware.AuthenticationMiddleware","django.contrib.messages.middleware.MessageMiddleware",'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

After trying to rule out some things, here's what I discovered. When I comment out SESSION_COOKIE_SECURE = TRUE and CSRF_COOKIE_SECURE = TRUE and SESSION_EXPIRE_AT_BROWSER_CLOSE = TRUE it works no problem.

If I just comment out CSRF_COOKIE_SECURE = TRUE it works fine. Something weird seems to be going on with how I'm handling CSRF... any help would be great.

Answer

Sounds to me like the site is not https if it works when you comment out that line? CSRF_COOKIE_SECURE=True makes the csrf token only work with ssl per the docs https://docs.djangoproject.com/en/1.7/ref/settings/#csrf-cookie-secure

https://en.xdnf.cn/q/72609.html

Related Q&A

Python model object validation

Im writing an interface to be used by two applications. This interface should use some DoSomethingRequest and DoSomethingResponse classes to do the communication.Is there any library that does some mod…

Cassandra 1.2 inserting/updating a blob column type using Python and the cql library

IntroI have a blob column on a Cassandra 1.2 column family, the table is defined as follows:CREATE TABLE objects (id text,obj blob,PRIMARY KEY (id) );The problem:The problem is that when I…

Using python with subprocess Popen

I am struggling to use subprocesses with python. Here is my task:Start an api via the command line (this should be no different than running any argument on the command line) Verify my API has come …

ipdb, multiple threads and autoreloading programs causing ProgrammingError

I am using ipdb debugger to debug multithreaded web applications locally (Django, Plone). Often ipdb seems to get confused because of the autoreload which happens when I am on the debug prompt. The res…

How to turn off logging buffer to get logs in real time with python command line tool?

I have a command line tool which produces plenty of logs. I want these logs to be sent to stdout as soon as theyre made. Right now, the program finishes everything (which can take several minutes), and…

How to tell if process is responding in Python on Windows

I am writing a python script to keep a buggy program open and I need to figure out if the program is not respoding and close it on windows. I cant quite figure out how to do this.

How to load and use a pretained PyTorch InceptionV3 model to classify an image

I have the same problem as How can I load and use a PyTorch (.pth.tar) model which does not have an accepted answer or one I can figure out how to follow the advice given.Im new to PyTorch. I am trying…

Append list to pandas DataFrame as new row with index

Despite of the numerous stack overflow questions on appending data to a dataframe I could not really find an answer to the following. I am looking for a straight forward solution to append a list as la…

IPC between Python and C#

I want to pass data between a Python and a C# application in Windows (I want the channel to be bi-directional) In fact I wanna pass a struct containing data about a network packet that Ive captured wit…

Saving matplotlib subplot figure to image file

Im fairly new to matplotlib and am limping along. That said, I havent found an obvious answer to this question.I have a scatter plot I wanted colored by groups, and it looked like plotting via a loop w…