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})
Related
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'
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')
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'"
I am trying to add a feature to where a new user needs to update his/her password on an initial login. I added a hidden BooleanField to my Profile model where default = True.
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
force_password_change = models.BooleanField(default=True)
However, when trying to use force_password_change in my views.py, it never returns the correct value that I set in django's admin page.
views.py
if request.method == 'POST':
...
user = authenticate(request, username=username, password=password)
changepass = UserProfile.objects.get(user=request.user)
if user:
if changepass.force_password_change == True:
changepass.force_password_change = False
changepass.save()
return HttpResponseRedirect('/login/register/')
elif changepass.force_password_change == False:
if user.is_active:
login(request, user)
return HttpResponseRedirect('/main/')
else:
return HttpResponse("Your account has been disabled.")
It is currently giving me this error
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\django\core\handlers\exception.py", line
41, in inner
response = get_response(request)
File "C:\Python34\lib\site-packages\django\core\handlers\base.py", line 187,
in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python34\lib\site-packages\django\core\handlers\base.py", line 185,
in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "start\views.py", line 20, in user_login
changepass = UserProfile.objects.get(user=request.user)
File "C:\Python34\lib\site-packages\django\db\models\manager.py", line 85,
in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Python34\lib\site-packages\django\db\models\query.py", line 380, in
get
self.model._meta.object_name
start.models.DoesNotExist: UserProfile matching query does not exist.
I also added AUTH_PROFILE_MODULE = 'start.UserProfile' to my settings.py, so that does not seem to be the problem.
You are forgetting to create UserProfile with the respected user
from django.db.models.signals import post_save
from models import UserProfile
from django.contrib.auth.models import User
def register(request):
if request.method == 'POST':
uf = UserForm(request.POST, prefix='user')
upf = UserProfileForm(request.POST, prefix='userprofile')
if uf.is_valid() and upf.is_valid():
user = uf.save()
userprofile = upf.save(commit=False)
userprofile.user = user
userprofile.save() # Are you missing this line ??
return django.http.HttpResponseRedirect(…something…)
This has nothing to do with boolean fields. The error is telling you that your specific User does not have a related entry in the UserProfile table.
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