The Django error known as MultiValueDictKeyError occurs when a key

I encountered a MultiValueDictKeyError while working in Django. The issue arises when trying to logout a user from my website using the following code:

In HTML


        </li>
                <li class="nav-item mr-3">
                  <a href="javascript:{document.getElementById('logout').submit()}" class="nav-link">
                  <i class="fas.fa-sign-out-alt"></i>Logout 
                  </a>
                  <form action="{% url 'logout'%}" method="POST" id="logout">
                    {% csrf_token %}
                    <input type="hidden>
                  </form>
                </li>

Below are the login and logout functions defined in 'accounts/views.py':


  def login(request):
      # request method
      if request.method == 'POST':
          #Saving the username and password in variables
          username = request.POST['username']
          password = request.POST['password']

          # Check if the username and password match using the authenticate function
          user = auth.authenticate(username=username, password=password)

          # If the user is found with the entered credentials, log them in
          if user is not None:
              auth.login(request, user)
              messages.success(request, "Welcome to BTRE.")
              return redirect('dashboard')
          # If the credentials do not match, display an error message and redirect to the login page
          else:
              messages.error(request, "Incorrect Username and/or Password. Please enter correct credentials")
              return redirect('login')
      else:
          return render (request, 'accounts/login.html')

  def logout(request):
      if request.method == 'POST':
          auth.logout(request)
          messages.success(request,"You are now logged out")
          return redirect('index')

Environment:

Request Method: POST Request URL:

Django Version: 3.0.2 Python Version: 3.8.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'pages.apps.PagesConfig', 'listings.apps.ListingsConfig', 'realtors.apps.RealtorsConfig', 'accounts.apps.AccountsConfig'] Installed 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']

Traceback (most recent call last): File "C:\Users\DD\Desktop\btre\venv\lib\site-packages\django\utils\datastructures.py", line 76, in getitem list_ = super().getitem(key)

During handling of the above exception ('username'), another exception occurred: File "C:\Users\DD\Desktop\btre\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\DD\Desktop\btre\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\DD\Desktop\btre\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\DD\Desktop\btre\accounts\views.py", line 12, in login username = request.POST['username'] File "C:\Users\DD\Desktop\btre\venv\lib\site-packages\django\utils\datastructures.py", line 78, in getitem raise MultiValueDictKeyError(key)

Exception Type: MultiValueDictKeyError at /accounts/logout Exception Value: 'username'

Answer №1

from django.urls import path
from . import views

urlpatterns = [
    path('login', views.login, name ='login'),
    path('logout', views.login, name ='logout'),
    path('register', views.register, name ='register'),
    path('dashboard', views.dashboard , name = 'dashboard')
]

I want to thank everyone for their assistance. After spending three hours troubleshooting, I finally discovered a small error in my urls.py file that was causing all the issues. Your time and help are greatly appreciated. Thank you once again.

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

Is there a way to confirm the presence of the username and password in my websql database for the login page?

Take a look at the code snippet below for my login page: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="style.css"> <script type="text/javascript" src="C:\Use ...

Substituting text in a document by utilizing two separate arrays: one holding the original text to be found and another storing the corresponding text for

I am facing a challenge with replacing specific text strings in a file. I have two arrays - one containing the strings that need to be located and replaced, and the other containing the replacement strings. fs.readFile("./fileName.L5X", "utf8", function( ...

unable to choose just one material ui checkbox

I'm new to using React and I'm currently developing a simple todo app with React JS and Material UI. To accomplish this, I've created two separate components - one for taking user input (TodoInput) and another for rendering each individual t ...

Is there a way to transform an angular 2 app.module into ES6 format?

import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; //specific imports remov ...

How can I create a cube with complete beveling using Three.js?

I'm struggling to create a beveled cube in my project. I have come across the THREE.ExtrudeGeometry snippet in the documentation here. However, when I tried it out, I only managed to achieve beveled sides on the top and bottom faces like this: https: ...

Receiving a "Maximum call exceeded" error when using Vue.js router guards for the beforeEach hook

As I work on my Firebase-VueJS app, I am implementing basic security rules with router guards. In my main.js file, I have added the following code to handle permissions based on the user's authentication status. However, I encounter an error 'vue ...

Using Vuejs to dynamically apply a class and trigger a function based on a specified condition

I am currently facing three small issues in my Vue app. The first problem involves class binding. I have a bootstrap card that displays a question and its related answers. When a user clicks on a radio input, their answer is saved and the other options are ...

Incorporating a new row in JQuery Datatable using an mdata array

I am currently using a datatable that retrieves its data through mData. var processURL="path" $.ajax( { type : "GET", url : processURL, cache : false, dataType : "json", success ...

Images that adjust to different screen sizes within a grid layout

I have four images that need to be aligned in the following layout: ____________ |1 |4 | |_____| | |2 |3| | |__|__|______| They must be flush against each other, occupy 100% of the viewport's width, and most importantly, be respon ...

React Material-UI Table - Universal and Group-Wide Application

I want to implement the functionality of "Apply To All" and "Apply to GroupBy" for the rows I'm working with using Material UI. I need to create a button for "Apply to All". This button will update all the columns on a row when the user makes chang ...

Ways to truncate text and include a "Read More" button within a v-for loop

The text in the "card-text" class is being retrieved from a Json file, but it's too long. I want to shorten the text and include a "Read More" button that expands the text when clicked on, but only for the specific card that was clicked. Is there a wa ...

Having difficulty accessing $scope beyond the function

One of the functions in my code is called getMail() $scope.getMail=function(){ $http.get(APISource). success(function(data) { $scope.mail =data; }). error(function(data) { console.log("error"); console.log(data); }); } In the succe ...

Modify the ColVis Appearance in Datatable Using JavaScript

Where can I modify the background color for the 'Hide/Show columns' label in the ColVis.js file? ...

Ace Code Editor: Turn off highlighted line beneath cursor

I am currently utilizing the Ace editor and would like to remove the shadowed line where the cursor is located. Here's an example Even after experimenting with different themes provided by Ace Mode Creator, the shadowed line still persists. Any sug ...

Is there a way for me to enable the functionality of the Edit button within a modal in order to update its

When I click the update button, my goal is to be able to edit the contents of the modal in the database. However, I am currently facing challenges with that process. The modal resides within my index.html file. Here are the details... Code from Modal and ...

Table expands to full width

I am facing an issue with a table that has a large number of elements. I would like the table to expand to the full width of the screen, but it slows down significantly when it does so. https://i.sstatic.net/s475I.png However, I have noticed that if I se ...

Having trouble with executing functions on an express js Route?

I'm currently exploring Node and Express, and I'm encountering an issue when trying to pass a function instead of plain text on my route. It seems that the documentation only mentions using res.send() method with text. Even when attempting to use ...

Unable to retrieve the iframe variable from the parent as it returns undefined

I am trying to retrieve a variable within an iframe from the parent index.html. Here is the index.html code: <!doctype html> <html lang="en-us> <head> <title>Test</title> </head> <body> <p>Test& ...

Tips for assigning a class name to a variable element within a react component?

I am interested in dynamically adding classes to an element. While I am familiar with methods using html-dom and passing a JavaScript expression to className, I am seeking a different approach. Is there a way to add classes similar to pushing them to an ar ...

The chart is failing to update with the data it obtained through Jquery

Scenario: I want to populate a chart using data fetched by Jquery. $.getJSON("/dashboard/", function(data, status) { var test_data=data console.log(test_data) chart.data.datasets[0].data=test_data; ...