MultiValueDictKeyError in django 1.11.18 - python

I am using Python 3.7 with Django 1.11.18. I have to connect to an Oracle 11g database and that is why the use of 1.11 version for django.
The below code was working for django 2.0.7 and python 3.7 but when i downgraded my version to 1.11.18 it s started giving me the error.
I am sending a post request via an HTML form. The post request has fields username and password. The python code to retrieve the same is :-
username = request.POST[‘username’]
password = request.POST[‘password’]
I also tried:-
username = request.POST.get(‘username’, False)
The above code picks up the default value even though a valid valuse is passed through my form.
Any idea why this is happening and how to solve it.
Edit:- The full part of the code is below
views.py
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request)
request.session['userName'] = username
return HttpResponse("SUCCESS")
else:
return HttpResponse("FAILURE")
HTML
$( "#loginForm" ).submit(function( event ) {
// Stop form from submitting normally
event.preventDefault();
var jqxhr = $.post( "http://127.0.0.1:8000/ScApp2/xxxx/", $( "#loginForm" ).serialize(), function() {
})
.done(function( data ) {
if( data == "SUCCESS")
window.location.href = 'http://127.0.0.1:8000/ScApp2/home/xxxx.html';
else
alert("Please check your username and password and try again.");
})
.fail(function() {
alert( "ERROR : Please contact the Support Team." );
});
});
TRACEBACK:-
[28/Jan/2019 17:12:24] "POST /xxxx/xxxx/ HTTP/1.1" 200 7
Internal Server Error: /xxxx/xxxx/ScorecardApp20/
Traceback (most recent call last):
File "c:\users\xxxx\xxxx\local\programs\python\python37\lib\site-packages\django\utils\datastructures.py", line 83, in __getitem__
list_ = super(MultiValueDict, self).__getitem__(key)
KeyError: 'username'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\users\xxxx\xxxx\local\programs\python\python37\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
response = get_response(request)
File "c:\users\xxxx\xxxx\local\programs\python\python37\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "c:\users\xxxx\xxxx\local\programs\python\python37\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\PythonWorkspace\xxxx\xxxx\views.py", line 67, in home
username = request.POST['username']
File "c:\users\xxxx\xxxx\local\programs\python\python37\lib\site-packages\django\utils\datastructures.py", line 85, in __getitem__
raise MultiValueDictKeyError(repr(key))
django.utils.datastructures.MultiValueDictKeyError: "'username'"

Related

Django debugger vs running From terminal

I'm trying to authenticate a basic django webapp with my firebase cloud db.
So the problem is when I login normally providing the appropriate username and password, the login is sucessfull and i get redirected to the home page.
But when I run a debugger I get an error saying :
Internal Server Error: /login/ Traceback (most recent call last):
File "c:\Users\moham\OneDrive\Desktop\Granular\web solution\web_solution\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "c:\Users\moham\OneDrive\Desktop\Granular\web solution\web_solution\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\moham\OneDrive\Desktop\Granular\web solution\Chosen_granular\apps\authentication\views.py", line 26, in login_view
if (firebase_authentication(user.email,password)):
**AttributeError: 'NoneType' object has no attribute 'email'**
And this is how my login view function looks like.
def login_view(request):
form = LoginForm(request.POST or None)
msg = None
if request.method == "POST":
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = authenticate(username=username, password=password)
if (firebase_authentication(user.email,password)):
#user = auth.get_user_by_email(user.email)
#request['uid']=user.uid
login(request, user)
return redirect("/")
else:
msg = 'Invalid credentials'
else:
msg = 'Error validating the form'
return render(request, "accounts/login.html", {"form": form, "msg": msg})

My Wikipedia-inspired Django project returns an error whenever I click an entry

I work with Django to create a Wikipedia-like app (course project). When I click one of my entries, I receive the following error:
TypeError: entry() got multiple values for argument 'title'
Here the view I created for entries in views.py:
#csrf_exempt
def entry(request, title):
flag = util.get_entry(title)
if flag is None:
form = SearchForm()
content = "The page you look for does not exist :("
return render(request, "encyclopedia/error.html", {"form": form, "content": content})
else:
form = SearchForm()
mdcontent = util.get_entry(title)
htmlcontent = markdowner.convert(mdcontent)
return render(request, "encyclopedia/entry.html", {
"title": title, "content": htmlcontent, "form": form
})
Do you notice multiple values for title? I'm new to Django and can't figure out the problem. Your help will be appreciated.
Traceback:
Request Method: GET
Request URL: http://localhost/wiki/CSS
Traceback (most recent call last):
File "/workspaces/79201800/wiki/env/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request)
File "/workspaces/79201800/wiki/env/lib/python3.10/site-packages/django/core/handlers/base.py", line 198, in _get_response response = wrapped_callback(request, title, *callback_args, **callback_kwargs)
File "/workspaces/79201800/wiki/env/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs)
Exception Type: TypeError at /wiki/CSS
Exception Value: entry() got multiple values for argument 'title'

Problen with generating token in login

Hello I would like help I have been trying to learn how to create token with django rest framework and pyjwt
But whenever I do it when I am going to use login it gives me an error I would like to know if it is due to the code since I have seen several videos and I have the same code or it is due to something on my computer and if so, how could I solve it, the error is the next
Internal Server Error: /api/login
Traceback (most recent call last):
File "D:\Users\ferna\Documents\Cursos\Youtube\auth.env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "D:\Users\ferna\Documents\Cursos\Youtube\auth.env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Users\ferna\Documents\Cursos\Youtube\auth.env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "D:\Users\ferna\Documents\Cursos\Youtube\auth.env\lib\site-packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "D:\Users\ferna\Documents\Cursos\Youtube\auth.env\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "D:\Users\ferna\Documents\Cursos\Youtube\auth.env\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "D:\Users\ferna\Documents\Cursos\Youtube\auth.env\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "D:\Users\ferna\Documents\Cursos\Youtube\auth.env\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "D:\Users\ferna\Documents\Cursos\Youtube\auth\users\views.py", line 37, in post
token = jwt.encode(payload, 'secret', algorithm='HS256').decode('utf-8')
AttributeError: 'str' object has no attribute 'decode'
[07/May/2021 21:18:23] ←[35;1m"POST /api/login HTTP/1.1" 500 96900←[0m
the code for view it's
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.exceptions import AuthenticationFailed
from .serializers import UserSerializer
from .models import User
import jwt, datetime
# Create your views here.
class RegisterView(APIView):
def post(self, request):
serializer = UserSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data)
class LoginView(APIView):
def post(self, request):
email = request.data['email']
password = request.data['password']
user = User.objects.filter(email=email).first()
if user is None:
raise AuthenticationFailed('User not found!')
if not user.check_password(password):
raise AuthenticationFailed('Incorrect password!')
payload = {
'id': user.id,
'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60),
'iat': datetime.datetime.utcnow()
}
token = jwt.encode(payload, 'secret', algorithm='HS256').decode('utf-8')
response = Response()
response.set_cookie(key='jwt', value=token, httponly=True)
response.data = {
'jwt': token
}
return response
I found actual problem.
The package PyJWT changed return type of jwt.encode(...) with version 2. From now it returns string instead of byte string. Link
After that use these codes:
encoded = jwt.encode({"some": "payload"}, key, algorithm="HS256")
result = jwt.decode(encoded, key, algorithms="HS256")
instead of that this:
result = jwt.encode(payload, 'secret', algorithm='HS256').decode('utf-8')

When data post to django api, ConnectionResetError: [Errno 54] occur

I'm recently learning how to use django as backend, and let react redux handle frontend. But when I try to implement login function in frontend, and post data to api, ConnectionResetError: [Errno 54] occurs.
I used django's User model to create user, and used rest_framework to create API for login. Then, using react with redux as frontend. When user login, it will trigger reducer to implement a login action with axios.post, but the serverside keeps showing errors. When I just login on API view page, it works fine. So I think the problem is with frontend, but I couldn't figure it out.
my API for login
class LoginAPIView(generics.GenericAPIView):
serializer_class = LoginSerializer
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data
return Response({
"user": UserSerializer(user,
context=self.get_serializer_context()).data,
"token": AuthToken.objects.create(user)[1]
})
my redux action to login
export const login = (username, password) => dispatch => {
const config = {
headers : {
"Content-Type": "application/json"
}
};
const body = {
"username" : username,
"password" : password
}
axios.post("/api/auth/login", body, config)
.then(res => {
dispatch({
type: LOGIN_SUCCESS,
payload: res.data
});
}).catch(err => {
console.log(err);
dispatch({
type: LOGIN_FAIL
})
});
};
And in my Login.js Component
onSubmit = e => {
e.preventDefault;
console.log(this.state.username, this.state.password);
this.props.login(this.state.username, this.state.password);
};
I use onSubmit to trigger event when user hit login button. I include consolo.log to check whether the data get correctly, and it works fine too.
When I check on Redux devTool on Chrome, neither LOGIN_SUCCESS nor LOGIN_FAIL been dispatched. And base on serverside's HTTP 200, I think the problem is not on backend. Somehow, when post succeeds​, the frontend can't receive the result.
[03/Aug/2019 19:20:40] "POST /api/auth/login HTTP/1.1" 200 139
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 58167)
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 650, in process_request_thread
self.finish_request(request, client_address)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 360, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 720, in __init__
self.handle()
File "/Users/kyle/Desktop/Todo/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 171, in handle
self.handle_one_request()
File "/Users/kyle/Desktop/Todo/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 179, in handle_one_request
self.raw_requestline = self.rfile.readline(65537)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 589, in readinto
return self._sock.recv_into(b)
ConnectionResetError: [Errno 54] Connection reset by peer
Update :
My url pattern in user
urlpatterns = [
path('api/auth', include('knox.urls')),
path('api/auth/user', UserAPIView.as_view()),
path('api/auth/register', RegisterAPIView.as_view()),
path('api/auth/login', LoginAPIView.as_view()),
path('api/auth/logout', KnoxViews.LogoutView.as_view(), name='knox_logout')
]

RawPostDataException: You cannot access body after reading from request's data stream

I am hosting a site on Google Cloud and I got everything to work beautifully and then all of the sudden I start getting this error..
01:16:22.222
Internal Server Error: /api/v1/auth/login/ (/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/core/handlers/exception.py:124)
Traceback (most recent call last):
File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/core/handlers/exception.py", line 39, in inner
response = get_response(request)
File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/core/handlers/base.py", line 249, in _legacy_get_response
response = self._get_response(request)
File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/rest_framework/views.py", line 474, in dispatch
response = self.handle_exception(exc)
File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/rest_framework/views.py", line 434, in handle_exception
self.raise_uncaught_exception(exc)
File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/rest_framework/views.py", line 471, in dispatch
response = handler(request, *args, **kwargs)
File "/base/data/home/apps/s~crs-portal/1.395605052160854207/authentication/views.py", line 42, in post
data = json.loads(request.body)
File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/rest_framework/request.py", line 359, in __getattribute__
return getattr(self._request, attr)
File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/http/request.py", line 263, in body
raise RawPostDataException("You cannot access body after reading from request's data stream")
RawPostDataException: You cannot access body after reading from request's data stream
I have no clue what this means, and endless googling has not solved my case in anyway..
Here's the code that is probably relevant:
views.py
class LoginView(views.APIView):
def post(self, request, format=None):
data = json.loads(request.body)
email = data.get('email', None)
password = data.get('password', None)
account = authenticate(email=email, password=password)
if account is not None:
if account.is_active:
login(request, account)
serialized = AccountSerializer(account)
return Response(serialized.data)
else:
return Response({
'status': 'Unauthorized',
'message': 'This account has been disabled.'
}, status=status.HTTP_401_UNAUTHORIZED)
else:
return Response({
'status': 'Unauthorized',
'message': 'Username/password combination invalid.'
}, status=status.HTTP_401_UNAUTHORIZED)
serializer.py
class AccountSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True, required=False)
confirm_password = serializers.CharField(write_only=True, required=False)
class Meta:
model = Account
fields = ('id', 'email', 'username', 'created_at', 'updated_at', 'full_name', 'password', 'confirm_password')
read_only_fields = ('created_at', 'updated_at',)
def create(self, validated_data):
return Account.objects.create(**validated_data)
def update(self, instance, validated_data):
instance.username = validated_data.get('username', instance.username)
instance.save()
password = validated_data.get('password', None)
confirm_password = validated_data.get('confirm_password', None)
if password and confirm_password and password == confirm_password:
instance.set_password(password)
instance.save()
update_session_auth_hash(self.context.get('request'), instance)
return instance
This is occuring is because you are trying to access the data from body
use -> data = json.loads(request.data)
Use request.data instead of request.body.
request.data does not read the data stream again.
hey thanks for the response but I figured it out! It wasn't working because I found a small bug where I am able to access the login page even though I am already logged in, so the error was caused by trying to login again. I fixed the issue by redirecting to home page if login page is tried to be reached

Categories