CSRF validation did not pass. The request has been cancelled. The failure occurred due to either a missing or incorrect CSRF token

Upon hitting the submit button in the login form, I encountered the following error message:

Forbidden (403) CSRF verification failed. Request aborted. CSRF token missing or incorrect.

settings.py

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

views.py

def contact_us(request):
    if request.method == "POST":
        con_name = request.POST['con_name']
        con_email = request.POST['con_email']
        con_company = request.POST['con_company']
        inquiry = request.POST['inquiry']
        con_message = request.POST['con_message']
        #context = RequestContext(request)
        #context_dict={'con_name':con_name}
        #context_dict.update(csrf(request))
        return render(request, 'contact_us.html', {'con_name':con_name})

    else:
        return render(request, 'contact_us.html',{})    

contact_us.html

<form id="contact-form" action="{% url 'contact_us' %}" method="post">
  {% csrf_token %}
  <div class="contact-form">
    <div class="contact-input">
      <div class="contact-inner">
        <input name="con_name" type="text" placeholder="Name *">
      </div>
      <div class="contact-inner">
        <input name="con_email" type="email" placeholder="Email *">
      </div>
    </div>
    <div class="contact-inner">
      <input name="con_company" type="text" placeholder="Company">
    </div>
    <div class="contact-select">
      <div class="form-item contact-inner">
        <span class="inquiry">
          <select name="inquiry" class="select-item">
              <option value="Your inquiry for">Your inquiry for</option>
              <option value="General Information Request">General Information Request</option>
              <option value="Partner Relations">Public Relations</option>
              <option value="Digital Marketing">Digital Marketing</option>
              <option value="Influencer Marketing">Influencer Marketing</option>
              <option value="Brand Creation">Brand Creation</option>
              <option value="Careers">Careers</option>
              <option value="Brand Creation">Web Development</option>
              <option value="Others">Others</option>
          </select>
          </span>
      </div>
    </div>
    <div class="contact-inner contact-message">
      <textarea name="con_message" placeholder="Please describe what you need."></textarea>
    </div>
    <div class="submit-btn mt-20">
      <button class="ht-btn ht-btn-md" type="submit">Send message</button>
      <p class="form-messege"></p>
    </div>
  </div>
</form>

I am relatively new to Django and web development, and I am struggling to identify the root of this issue. What steps can I take to resolve the CSRF verification error? Can someone provide guidance on how to fix this problem?

Answer №1

To include the csrf_token in your template, you must pass RequestContext in the render_to_response function.

In your views.py file, add the following code:

from django.template import RequestContext

...

return render_to_response('fileupload/upload.html', {'form': c['UploadFileForm']}, RequestContext(request))

By including RequestContext(request), the csrf token will be passed to the template.

For more information, check out this Link as well.

Answer №2

When encountering a similar issue, I found that inserting "{% csrf_token %}" before individual input tags, especially when they were not grouped together or separated by other tags, helped resolve the problem.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Differences in Print Layout Between Chrome and Firefox when Viewing a PHP Website

I have been working on creating a print command to print a specific div, and I have managed to successfully run the print command using default methods like CTRL + P and also with a button click. The Issue: However, I have encountered a problem where the ...

Inherit margins from child elements with fixed positions

Below is a very basic code example to consider: <div id="parent"> <div id="child"> Test it </div> </div> This code snippet includes the following CSS styles: #parent{ position:relative; margin-left:200px; color:#FFF; } #chi ...

Issue with Material-UI Nested Checkbox causing parent DOM to not update upon selection changes

Currently, I am integrating a nested checkbox feature from a working example into my application. The functionality of the checkboxes covers seven different scenarios: - Scenario - No children, no parent selected - Select the parent -> select both pa ...

The background refuses to cooperate, soaring upward only to be abruptly sliced in two

I am in the process of creating a website login window with an image background, but I'm experiencing issues where the image is being cut in half and moved up. Here is the code snippet I am currently using: .loginbody { background: url(img/LoginB ...

Retrieving Records within a Specific Date Range for Check-ins and Check-outs

Our team is currently working on developing booking software that requires handling different room pricing based on specific dates. Each room has distinct pricing for weekdays and weekends. ROOM 1 Pricing 1: September 1st - November 3rd, Weekday: $100, W ...

Placement of the Zend submit button

How can I position the submit button at the bottom of a form wrapped in an HTML table, when calling two forms from the same controller? Currently, the button is stuck between the first form and the table. I attempted to assign the element in my controller ...

Assistance needed to identify CSS issue specifically in FireFox browser

Working on a new webpage and encountered an issue with the HTML markup: <!DOCTYPE html> <html lang="en> <head> <meta charset="utf-8"> <title>TileTabs</title> <link rel="stylesheet" href="css/style.css" t ...

The JQuery function .load() is not functioning correctly

How can I dynamically load a webpage's content into a div using JavaScript and jQuery? Here's what I have tried: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> When a s ...

Troubleshooting the issue with ajax loadXml callback functionality

My table is empty and I can't figure out where the mistake is. I want to use the console to debug, but I'm not sure how. Update: I found a working sample here http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_xml2. I used similar code, bu ...

Preventing users from entering past dates in Angular 6 - A step-by-step guide

Here is my current code snippet: ngOnInit() { let now = new Date(); this.date = formatDate(now, "dd/mm/yyyy",'en-US'); console.log("dateFormat :",this.date); } This is the html part of my code: <input type="date" [min]={{da ...

Tips for locating a specific div based on its background color

Take a look at this code featuring a grid - can you figure out how many cells are colored yellow and more? Check it out here ...

Best practice for encapsulating property expressions in Angular templates

Repeating expression In my Angular 6 component template, I have the a && (b || c) expression repeated 3 times. I am looking for a way to abstract it instead of duplicating the code. parent.component.html <component [prop1]="1" [prop2]="a ...

As soon as I hover over my icon to enlarge it, I notice that my entire page starts to

Whenever I hover over my icon, the font size increases causing the div to expand slightly and move the page. This doesn't look great. How can I prevent the div from resizing when hovering over the icon? Here's my code: <div className="bg- ...

How to disable typescript eslint notifications in the terminal for .js and .jsx files within a create-react-app project using VS Code

I'm currently in the process of transitioning from JavaScript to TypeScript within my create-react-app project. I am facing an issue where new ESLint TypeScript warnings are being flagged for my old .js and .jsx files, which is something I want to avo ...

Ensure the scrollbar is noticeable and personalized solely within a designated div, such as the left side menu

In the left side menu, I have set the overflow-y: scroll property and a fixed height that is smaller than the entire page's height. I am trying to make the scrollbar always visible only within this left menu. I attempted using -webkit-scrollbar and -w ...

Submenu failing to appear

After reading a discussion on dropdown menu issues on a popular forum, I am still unable to locate the error on my website: . The submenu on the main top menu is not functioning as it should. My attempt to resolve the problem by changing the overflow sett ...

Obtaining values from multi-dimensional arrays with JavaScript and node.js

I have a data structure like this: let arr = [ ['animal','lion'], ['plant','rose'], ['tree','coconut'], ] I want to reformat it to look like this: ['animal','lion' ...

Positioning HTML elements using CSS and avoiding the use of tables

I'm struggling with my clear CSS declarations. This is how I'd like it to appear: View the Fiddle demo HTML: <div id="timesheeteditor"> <div id="weekselector"> <div>Week 1</div> <div>Week 2</div> ...

Arranging Data in Arrays using Angular 4 GroupBy Feature

I'm working with an array structured like this: var data = [ { student: "sam", English: 80, Std: 8 }, { student: "sam", Maths: 80, Std: 8 }, { student: "john", English: 80, Std: 8 }, { student: "j ...

Exploring the functionalities of can-deactivate without incorporating routing

I'm facing an issue with a parent component and multiple child components. The parent component contains a form, while each child component also has its own form. Unfortunately, all child components share the same route as the parent component and hav ...