Django login method gives recursion error - django

I tried making a custom authentication view that saves the user in the session using login(request, user) but it gives me
maximum recursion depth exceeded while calling a Python object
I tried importing the login method with from django.contrib.auth import login as django_login as to not confuse methods, but it still did not work.
Authentication works just fine without the login method, but it doesn't save the user in the session, so it's no use.
Here is the full views.py file:
from django.utils.translation import ugettext as _
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.views import APIView
from rest_framework.response import Response
from rest.models import User
from .serializers import UserSerializer
from django.contrib.auth import get_user_model
from django.contrib.auth import authenticate as django_authenticate
from django.contrib.auth import login as django_login
from django.contrib.auth.hashers import check_password
import json
class UserCreateAPIView(generics.CreateAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = (AllowAny,)
class Authentication(authentication.BaseAuthentication):
def authenticate(self, request):
email = request.POST.get('email', None)
password = request.POST.get('password', None)
if not email or not password:
raise exceptions.AuthenticationFailed(_('No credentials provided.'))
credentials = {
get_user_model().USERNAME_FIELD: email,
'password': password
}
user = django_authenticate(**credentials)
if user is None:
raise exceptions.AuthenticationFailed(_('Invalid username/password.'))
if not user.is_active:
raise exceptions.AuthenticationFailed(_('User inactive or deleted.'))
django_login(request, user)
return (user, None) # authentication successful
class LoginView(APIView):
authentication_classes = (SessionAuthentication, Authentication)
permission_classes = (IsAuthenticated,)
def post(self, request, format=None):
content = {
'user': str(request.user),
'auth': str(request.auth),
}
return Response(content)
def CheckLoginView(requst):
current_user = requst.user
return current_user
Here is the traceback:
response = get_response(request) …
▶ Local vars
/var/www/cnmb10a/venv/lib/python3.7/site-packages/django/core/handlers/base.py in _get_response
response = self.process_exception_by_middleware(e, request) …
▶ Local vars
/var/www/cnmb10a/venv/lib/python3.7/site-packages/django/core/handlers/base.py in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs) …
▶ Local vars
/var/www/cnmb10a/venv/lib/python3.7/site-packages/django/views/decorators/csrf.py in wrapped_view
return view_func(*args, **kwargs) …
▶ Local vars
/var/www/cnmb10a/venv/lib/python3.7/site-packages/django/views/generic/base.py in view
return self.dispatch(request, *args, **kwargs) …
▶ Local vars
/var/www/cnmb10a/venv/lib/python3.7/site-packages/rest_framework/views.py in dispatch
response = self.handle_exception(exc) …
▶ Local vars
/var/www/cnmb10a/venv/lib/python3.7/site-packages/rest_framework/views.py in handle_exception
self.raise_uncaught_exception(exc) …
▶ Local vars
/var/www/cnmb10a/venv/lib/python3.7/site-packages/rest_framework/views.py in raise_uncaught_exception
raise exc …
▶ Local vars
/var/www/cnmb10a/venv/lib/python3.7/site-packages/rest_framework/views.py in dispatch
self.initial(request, *args, **kwargs) …
▶ Local vars
/var/www/cnmb10a/venv/lib/python3.7/site-packages/rest_framework/views.py in initial
self.perform_authentication(request) …
▶ Local vars
/var/www/cnmb10a/venv/lib/python3.7/site-packages/rest_framework/views.py in perform_authentication
request.user …
▶ Local vars
/var/www/cnmb10a/venv/lib/python3.7/site-packages/rest_framework/request.py in user
self._authenticate() …
▶ Local vars
/var/www/cnmb10a/venv/lib/python3.7/site-packages/rest_framework/request.py in _authenticate
user_auth_tuple = authenticator.authenticate(self) …
▶ Local vars
/var/www/cnmb10a/cnmb10a/rest/auth_api/views.py in authenticate
django_login(request, user) …
▶ Local vars
/var/www/cnmb10a/venv/lib/python3.7/site-packages/django/contrib/auth/__init__.py in login
if hasattr(request, 'user'): …
▶ Local vars
/var/www/cnmb10a/venv/lib/python3.7/site-packages/rest_framework/request.py in user
self._authenticate() …
▶ Local vars
/var/www/cnmb10a/venv/lib/python3.7/site-packages/rest_framework/request.py in _authenticate
user_auth_tuple = authenticator.authenticate(self) …
▶ Local vars
/var/www/cnmb10a/cnmb10a/rest/auth_api/views.py in authenticate
django_login(request, user) …
▶ Local vars
/var/www/cnmb10a/venv/lib/python3.7/site-packages/django/contrib/auth/__init__.py in login
if hasattr(request, 'user'): …
▶ Local vars
/var/www/cnmb10a/venv/lib/python3.7/site-packages/rest_framework/request.py in user
self._authenticate() …
▶ Local vars
/var/www/cnmb10a/venv/lib/python3.7/site-packages/rest_framework/request.py in _authenticate
user_auth_tuple = authenticator.authenticate(self) …
▶ Local vars
/var/www/cnmb10a/cnmb10a/rest/auth_api/views.py in authenticate
django_login(request, user) …
▶ Local vars
The last 4 methods just repeat over and over again.

django.contrib.auth.authenticate will call the backend to try to authenticate a user.
By calling it in your authentication backend, it will loop forever because django.contrib.auth.authenticate will be calling you backend which will call the function and so on.
So you need to hereto from the authentication method your are trying to override and call super().authenticate(request) instead of django.contrib.auth.authenticate.

The problem seemed to be that the django_login() function called the authenticate() that I wrote, which in turn called django_login() again.
The solution was to remove django_login() from inside authenticate() and add it to LoginView(), so it looks like this:
authentication_classes = (SessionAuthentication, Authentication)
permission_classes = (IsAuthenticated,)
def post(self, request, format=None):
content = {
'user': str(request.user),
'auth': str(request.auth),
}
django_login(request, request.user)
return Response(content)

Related

__init__() missing 1 required positional argument: 'get_response' error on Django HttpOnly JWT solution

I currently have a Django setup that followed the guide below. Pretty much, it's a workaround that allows for HTTPOnly cookies to be used with Django Rest Framework JWT authentication. It worked fine in Django 3.2, but I'm attempting to upgrade to Django 4, and I'm now running into the error below
How to store JWT tokens in HttpOnly cookies with DRF djangorestframework-simplejwt package?
Error:
__init__() missing 1 required positional argument: 'get_response'
I'm still a bit new to Django and DRF, so I have no idea what could be going on.
Edit:
Apologies, forgot to add some details. The error is in the following code, on CSRFCheck():
from rest_framework_simplejwt.authentication import JWTAuthentication
from django.conf import settings
from rest_framework.authentication import CSRFCheck
from rest_framework import exceptions
def enforce_csrf(request):
# Enforce CSRF validation.
check = CSRFCheck()
check.process_request(request)
# populates request.META['CSRF_COOKIE'], which is used in process_view()
reason = check.process_view(request, None, (), {})
if reason:
# CSRF failed, bail with explicit error message
raise exceptions.PermissionDenied('CSRF Failed: %s' % reason)
class CustomAuthentication(JWTAuthentication):
def authenticate(self, request):
header = self.get_header(request)
if header is None:
raw_token = request.COOKIES.get(settings.SIMPLE_JWT['AUTH_COOKIE']) or None
else:
raw_token = self.get_raw_token(header)
if raw_token is None:
return None
validated_token = self.get_validated_token(raw_token)
enforce_csrf(request)
return self.get_user(validated_token), validated_token
Traceback messages:
(Full error: jsfiddle.net/Luizram/t7u03cqy/1 )
/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py, line 55, in inner
return inner
else:
#wraps(get_response)
def inner(request):
try:
response = get_response(request) <- Line 55
…
except Exception as exc:
response = response_for_exception(request, exc)
return response
return inner
Local vars
/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py, line 197, in _get_response
if response is None:
wrapped_callback = self.make_view_atomic(callback)
# If it is an asynchronous view, run it in a subthread.
if asyncio.iscoroutinefunction(wrapped_callback):
wrapped_callback = async_to_sync(wrapped_callback)
try:
response = wrapped_callback(request, *callback_args, **callback_kwargs) <- Line 197
…
except Exception as e:
response = self.process_exception_by_middleware(e, request)
if response is None:
raise
# Complain if the view returned None (a common error).
Local vars
/usr/local/lib/python3.8/site-packages/django/views/decorators/csrf.py, line 54, in wrapped_view
def csrf_exempt(view_func):
"""Mark a view function as being exempt from the CSRF view protection."""
# view_func.csrf_exempt = True would also work, but decorators are nicer
# if they don't have side effects, so return a new function.
def wrapped_view(*args, **kwargs):
return view_func(*args, **kwargs) <- Line 54
…
wrapped_view.csrf_exempt = True
return wraps(view_func)(wrapped_view)
Local vars
/usr/local/lib/python3.8/site-packages/django/views/generic/base.py, line 84, in view
self = cls(**initkwargs)
self.setup(request, *args, **kwargs)
if not hasattr(self, "request"):
raise AttributeError(
"%s instance has no 'request' attribute. Did you override "
"setup() and forget to call super()?" % cls.__name__
)
return self.dispatch(request, *args, **kwargs) <- Line 84
…
view.view_class = cls
view.view_initkwargs = initkwargs
# __name__ and __qualname__ are intentionally left unchanged as
# view_class should be used to robustly determine the name of the view
Local vars
/usr/local/lib/python3.8/site-packages/rest_framework/views.py, line 509, in dispatch
self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
response = handler(request, *args, **kwargs)
except Exception as exc:
response = self.handle_exception(exc) <- Line 509
…
self.response = self.finalize_response(request, response, *args, **kwargs)
return self.response
def options(self, request, *args, **kwargs):
"""
Local vars
/usr/local/lib/python3.8/site-packages/rest_framework/views.py, line 469, in handle_exception
exception_handler = self.get_exception_handler()
context = self.get_exception_handler_context()
response = exception_handler(exc, context)
if response is None:
self.raise_uncaught_exception(exc) <- Line 469
…
response.exception = True
return response
def raise_uncaught_exception(self, exc):
if settings.DEBUG:
Local vars
/usr/local/lib/python3.8/site-packages/rest_framework/views.py, line 480, in raise_uncaught_exception
def raise_uncaught_exception(self, exc):
if settings.DEBUG:
request = self.request
renderer_format = getattr(request.accepted_renderer, 'format')
use_plaintext_traceback = renderer_format not in ('html', 'api', 'admin')
request.force_plaintext_errors(use_plaintext_traceback)
raise exc <- Line 480
…
# Note: Views are made CSRF exempt from within `as_view` as to prevent
# accidental removal of this exemption in cases where `dispatch` needs to
# be overridden.
def dispatch(self, request, *args, **kwargs):
"""
Local vars
/usr/local/lib/python3.8/site-packages/rest_framework/views.py, line 497, in dispatch
self.args = args
self.kwargs = kwargs
request = self.initialize_request(request, *args, **kwargs)
self.request = request
self.headers = self.default_response_headers # deprecate?
try:
self.initial(request, *args, **kwargs) <- Line 497
…
# Get the appropriate handler method
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(),
self.http_method_not_allowed)
else:
Local vars
/usr/local/lib/python3.8/site-packages/rest_framework/views.py, line 414, in initial
request.accepted_renderer, request.accepted_media_type = neg
# Determine the API version, if versioning is in use.
version, scheme = self.determine_version(request, *args, **kwargs)
request.version, request.versioning_scheme = version, scheme
# Ensure that the incoming request is permitted
self.perform_authentication(request) <- Line 414
…
self.check_permissions(request)
self.check_throttles(request)
def finalize_response(self, request, response, *args, **kwargs):
"""
Returns the final response object.
Local vars
/usr/local/lib/python3.8/site-packages/rest_framework/views.py, line 324, in perform_authentication
"""
Perform authentication on the incoming request.
Note that if you override this and simply 'pass', then authentication
will instead be performed lazily, the first time either
`request.user` or `request.auth` is accessed.
"""
request.user <- Line 324
…
def check_permissions(self, request):
"""
Check if the request should be permitted.
Raises an appropriate exception if the request is not permitted.
"""
Local vars
/usr/local/lib/python3.8/site-packages/rest_framework/request.py, line 227, in user
def user(self):
"""
Returns the user associated with the current request, as authenticated
by the authentication classes provided to the request.
"""
if not hasattr(self, '_user'):
with wrap_attributeerrors():
self._authenticate() <- Line 227
…
return self._user
#user.setter
def user(self, value):
"""
Sets the user on the current request. This is necessary to maintain
Local vars
/usr/local/lib/python3.8/site-packages/rest_framework/request.py, line 380, in _authenticate
def _authenticate(self):
"""
Attempt to authenticate the request using each authentication instance
in turn.
"""
for authenticator in self.authenticators:
try:
user_auth_tuple = authenticator.authenticate(self) <- Line 380
…
except exceptions.APIException:
self._not_authenticated()
raise
if user_auth_tuple is not None:
self._authenticator = authenticator
Local vars
/django/users/authenticate.py, line 30, in authenticate
if header is None:
raw_token = request.COOKIES.get(settings.SIMPLE_JWT['AUTH_COOKIE']) or None
else:
raw_token = self.get_raw_token(header)
if raw_token is None:
return None
validated_token = self.get_validated_token(raw_token)
enforce_csrf(request) <- Line 30
…
return self.get_user(validated_token), validated_token
Local vars
/django/users/authenticate.py, line 10, in enforce_csrf
from rest_framework.authentication import CSRFCheck
from rest_framework import exceptions
def enforce_csrf(request):
# Enforce CSRF validation.
check = CSRFCheck() <- Line 10
…
check.process_request(request)
# populates request.META['CSRF_COOKIE'], which is used in process_view()
reason = check.process_view(request, None, (), {})
if reason:
# CSRF failed, bail with explicit error message

How do I view the profile of the authenticated user in Django Rest Framework using the Token

I am learning DRF and creating a simple DRF app that lets user login, and view the profile and update the profile. I am using Django's default User model and using Knox for Token Authentication (if it can be done easier using Django Rest Authentication, please let me know and also tell me the procedure).
I have successfully created the API to register and login the user which works fine, but I am stuck at showing the profile to the Authenticated User through a Token.
I am only one Model that is Details which acts as to store the Profile details of the user. I have LoginSerializer which is connected to Login API and MainUserSerializer & UserSerializer, both of which are connected to User API (which acts to show the Profile details on frontend).
I have tried a lot, searched everywhere, but all they show is how to authenticate the user with token through a url (some thing like using curl https://localhost:8000/api/user... etc.), postman, somehing like http post -a... command in terminal and other ways, but I don't want to test or implement using these ways. I want something that if I open my user profile url after logging in the user using the link localhost:8000/user, then at the backend it should do like following as mentioned here enter link description here:
import requests
url = 'http://127.0.0.1:8000/hello/'
headers = {'Authorization': 'Token 9054f7aa9305e012b3c2300408c3dfdf390fcddf'}
r = requests.get(url, headers=headers)
I have tried really hard, but I am unable to successfully go to the details page by authenticating user via token.
My models.py is:
from django.db import models
# Create your models here.
from django.contrib.auth.models import User
class Detail(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
file = models.FileField(verbose_name="CSV File", upload_to='csv_files')
file_desc = models.TextField("CSV File Description")
def __str__(self):
return ("{} ({} {})".format(self.user.email, self.user.first_name, self.user.last_name))
def __unicode__(self):
return (self.file_desc)
My serializers.py is:
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from .models import Detail
from rest_framework import serializers
class MainUserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('email',)
class UserSerializer(serializers.ModelSerializer):
usr = MainUserSerializer()
class Meta:
model = Detail
fields = ['usr', 'file', 'file_desc']
class LoginSerializer(serializers.Serializer):
email = serializers.EmailField()
password = serializers.CharField()
def validate(self, data):
user = authenticate(**{'username': data['email'], 'password': data['password']})
if user and user.is_active:
return user
raise serializers.ValidationError('Incorrect Credentials Passed.')
My views.py is:
import requests
from rest_framework import permissions
from knox.models import AuthToken
from .serializers import UserSerializer, LoginSerializer
from django.shortcuts import redirect
from rest_framework.renderers import TemplateHTMLRenderer
from rest_framework.views import APIView
from django.urls import reverse
from django.http import HttpResponseRedirect
class LoginAPIHTML(APIView):
renderer_classes = [TemplateHTMLRenderer]
template_name = 'accounts/login.html'
def get(self, request):
serializer = LoginSerializer()
return Response({'serializer': serializer})
def post(self, request):
serializer = LoginSerializer(data=request.data)
if not serializer.is_valid():
return Response({'serializer': serializer})
user = serializer.validated_data
url = 'http://' + str(request.get_host()) + str(reverse('user', args=None))
headers = {
'Authorization': 'Token ' + str(AuthToken.objects.create(user)[1])
}
r = requests.get(url, headers=headers, format='json')
return HttpResponseRedirect(r)
My urls.py is:
from django.urls import path, include
from .views import LoginAPIHTML
urlpatterns = [
path('api/v1/', include('knox.urls')),
path('login', LoginAPIHTML.as_view(), name='login'),
path('user', UserAPI.as_view(), name='user'),
]
and below is my settings.py:
INSTALLED_APPS = [
'accounts',
'rest_framework',
'rest_framework.authtoken',
'knox',
...
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'knox.auth.TokenAuthentication',
]
}
REST_AUTH_TOKEN_MODEL = 'knox.models.AuthToken'
REST_AUTH_TOKEN_CREATOR = 'project.apps.accounts.utils.create_knox_token'
Whenever, I put the correct credentials in the Login API at localhost:8000/login, then instead of redirecting to the details page at localhost:8000/user, I get the following error:
TypeError at /login
quote_from_bytes() expected bytes
Request Method: POST
Request URL: http://127.0.0.1:8000/login
Django Version: 4.0.3
Exception Type: TypeError
Exception Value:
quote_from_bytes() expected bytes
Traceback Switch to copy-and-paste view
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py, line 55, in inner
response = get_response(request) …
Local vars
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py, line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs) …
Local vars
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\csrf.py, line 54, in wrapped_view
return view_func(*args, **kwargs) …
Local vars
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\generic\base.py, line 84, in view
return self.dispatch(request, *args, **kwargs) …
Local vars
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py, line 509, in dispatch
response = self.handle_exception(exc) …
Local vars
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py, line 469, in handle_exception
self.raise_uncaught_exception(exc) …
Local vars
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py, line 480, in raise_uncaught_exception
raise exc …
Local vars
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py, line 506, in dispatch
response = handler(request, *args, **kwargs) …
Local vars
C:\Users\Khubaib Khawar\Downloads\Meistery\Round2\backend_dev_trial_ass_r2\accounts\views.py, line 202, in post
return HttpResponseRedirect(r) …
Local vars
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\http\response.py, line 538, in __init__
self["Location"] = iri_to_uri(redirect_to) …
Local vars
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\encoding.py, line 139, in iri_to_uri
return quote(iri, safe="/#%[]=:;$&()+,!?*#'~") …
Local vars
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\urllib\parse.py, line 870, in quote
return quote_from_bytes(string, safe) …
Local vars
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\urllib\parse.py, line 895, in quote_from_bytes
raise TypeError("quote_from_bytes() expected bytes") …
Local vars
I am fed up of this. It would be better if it sets up either using Knox or using Django Rest Authentication.
This should be of help:
https://studygyaan.com/django/django-rest-framework-tutorial-register-login-logout
I use this has a guide anytime am using Knox with drf.
Looking at the error logs you posted:
Local vars C:\Users\Khubaib Khawar\Downloads\Meistery\Round2\backend_dev_trial_ass_r2\accounts\views.py, line 202, in post return HttpResponseRedirect(r) …
HttpResponseRedirect expects the url or endpoint to be redirected to.
But the variable r is returning a response from the GET request made at:
r = requests.get(url, headers=headers, format='json')
hence the error:
raise TypeError("quote_from_bytes() expected bytes") …
I think this is similar to :
TypeError: quote_from_bytes() expected bytes after redirect
Based on your second comment:
you could try based off your code:
from rest_framework.response import Response
....
r = requests.get(url, headers=headers, format='json')
return Response(r.json(), status=status.HTTP_200_OK)
or
You could try separating your login view from your profile view. There is something called single responsibility in
SOLID principle. your login view should authenticate the user and return a valid token. And your profile view should be a protected view
that requires the user to be authenticated and has the right permission to view his user profile.
your profile view would look like this:
from rest_framework import mixins, authentication, permissions, status, viewsets
from rest_framework.response import Response
from core import models
from users.serializers import UserProfileSerializer
class UserProfileViewSet(viewsets.GenericViewSet,
mixins.ListModelMixin,
mixins.CreateModelMixin,
mixins.UpdateModelMixin,
):
"""User profile endpoint"""
authentication_classes = (authentication.TokenAuthentication, )
permission_classes = (permissions.IsAuthenticated,)
queryset = models.UserProfile.objects.all()
serializer_class = UserProfileSerializer
def get_queryset(self):
return models.UserProfile.objects.filter(
user=self.request.user.id)
def perform_create(self, serializer):
return serializer.save(user=self.request.user)
def update(self, request, *args, **kwargs):
user_obj = models.UserProfile.objects.get(id=kwargs['pk'])
user = request.user
if user_obj.user.id == user.id:
serializer = UserProfileSerializer(
user_obj,
data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(
serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
else:
return Response(
'Unauthorized',
status=status.HTTP_401_UNAUTHORIZED)
I hope this helps

Unable to perform conditional redirect from a class based view Django

I am trying to redirect a user who has already registered to a different view. here is the code for the views.py
However when qs.exists() = true I get an error
'The view Lpage.views.homeview didn't return an HttpResponse object. It returned None instead.'
I am a beginner have read the documentation but unable to find where i am going worng.
Thanks
from django.shortcuts import render, redirect
from django.views import View
from Lpage.forms import SubscriberEntryForm
from Lpage.models import Subscriber
class homeview(View):
def get(self,request):
msg = request.session.get('msg', False)
if(msg):
del(request.session['msg'])
return render(request,'Lpage/index.html')
def post(self, request):
form = SubscriberEntryForm(request.POST or None)
if form.is_valid():
obj = form.save(commit=False)
qs = Subscriber.objects.filter(email__iexact=obj.email)
if qs.exists():
return redirect('messageview')
else:
obj.save()
request.session['msg'] = "msg"
return redirect(request.path)
def messageview(request):
return render(request,'Lpage/messages.html',{})
Here is the error message
ValueError at /
The view Lpage.views.homeview didn't return an HttpResponse object. It returned None instead.
Request Method: POST
Request URL: http://localhost:8000/
Django Version: 3.2.7
Exception Type: ValueError
Exception Value:
The view Lpage.views.homeview didn't return an HttpResponse object. It returned None instead.
Exception Location: C:\Users\Ganesamurthi\anaconda3\lib\site-packages\django\core\handlers\base.py, line 309, in check_response
Python Executable: C:\Users\Ganesamurthi\anaconda3\python.exe
Python Version: 3.8.5
Python Path:
['D:\dreamdoors\dd',
'C:\Users\Ganesamurthi\anaconda3\python38.zip',
'C:\Users\Ganesamurthi\anaconda3\DLLs',
'C:\Users\Ganesamurthi\anaconda3\lib',
'C:\Users\Ganesamurthi\anaconda3',
'C:\Users\Ganesamurthi\anaconda3\lib\site-packages',
'C:\Users\Ganesamurthi\anaconda3\lib\site-packages\win32',
'C:\Users\Ganesamurthi\anaconda3\lib\site-packages\win32\lib',
'C:\Users\Ganesamurthi\anaconda3\lib\site-packages\Pythonwin']
Server time: Wed, 29 Sep 2021 05:23:43 +0000
Traceback Switch to copy-and-paste view
C:\Users\Ganesamurthi\anaconda3\lib\site-packages\django\core\handlers\exception.py, line 47, in inner
response = get_response(request) …
▶ Local vars
C:\Users\Ganesamurthi\anaconda3\lib\site-packages\django\core\handlers\base.py, line 188, in _get_response
self.check_response(response, callback) …
▶ Local vars
C:\Users\Ganesamurthi\anaconda3\lib\site-packages\django\core\handlers\base.py, line 309, in check_response
raise ValueError( …
▶ Local vars
redirect expects you to pass a URL but you gave it messageview, which is a view class in fact.
So you need to give redirect to the URL of messageview.

django.urls.exceptions.NoReverseMatch: Reverse for 'user-list' not found. 'user-list' is not a valid view function or pattern name

Tutorial 5: Relationship and Hyperlink API Errors
Tutorial link address is:https://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis/
I tried query-related solutions, and encountered similar problems on stackoverflow, but after testing, I still couldn't use them.
views.py
class SnippetList(generics.ListCreateAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
class SnippetDetail(generics.RetrieveDestroyAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly)
class UserList(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetail(generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
#api_view(['GET'])
def api_root(request, format=None):
return Response({
'users': reverse('user-list', request=request, format=format),
'snippets': reverse('snippet-list', request=request, format=format),
})
class SnippetHighlight(generics.GenericAPIView):
queryset = Snippet.objects.all()
renderer_classes = [renderers.StaticHTMLRenderer]
def get(self, request, *args, **kwargs):
snippet = self.get_object()
return Response(snippet.highlighted)
urls.py
urlpatterns = format_suffix_patterns([
path('', views.api_root),
path('snippets/', views.SnippetList.as_view(), name='snippet-list'),
path('snippets/<int:pk>/', views.SnippetDetail.as_view(), name='snippet-detail'),
path('snippets/<int:pk>/highlight/', views.SnippetHighlight.as_view(), name='snippet-highlight'),
path('users/', views.UserList.as_view(), name='user-list'),
path('users/<int:pk>/', views.UserDetail.as_view(), name='user-detail'),
])
urlpatterns += [
path(r'api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
serializers.py
class SnippetSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html')
class Meta:
model = Snippet
fields = ['url', 'id', 'highlight', 'owner',
'title', 'code', 'linenos', 'language', 'style']
class UserSerializer(serializers.HyperlinkedModelSerializer):
snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True)
class Meta:
model = User
fields = ['url', 'id', 'username', 'snippets']
Traceback error:
Traceback:
File "C:\Anaconda3\envs\python36\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request)
File "C:\Anaconda3\envs\python36\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request)
File "C:\Anaconda3\envs\python36\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Anaconda3\envs\python36\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 54. return view_func(*args, **kwargs)
File "C:\Anaconda3\envs\python36\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs)
File "C:\Anaconda3\envs\python36\lib\site-packages\rest_framework\views.py" in dispatch 505. response = self.handle_exception(exc)
File "C:\Anaconda3\envs\python36\lib\site-packages\rest_framework\views.py" in handle_exception 465. self.raise_uncaught_exception(exc)
File "C:\Anaconda3\envs\python36\lib\site-packages\rest_framework\views.py" in raise_uncaught_exception 476. raise exc
File "C:\Anaconda3\envs\python36\lib\site-packages\rest_framework\views.py" in dispatch 502. response = handler(request, *args, **kwargs)
File "C:\Anaconda3\envs\python36\lib\site-packages\rest_framework\decorators.py" in handler 50. return func(*args, **kwargs)
File "C:\Users\Ze Ran Lu\Desktop\swie\text\tutorials\snippets\views.py" in api_root 205. 'users': reverse('user-list'),
File "C:\Anaconda3\envs\python36\lib\site-packages\rest_framework\reverse.py" in reverse 47. url = _reverse(viewname, args, kwargs, request, format, **extra)
File "C:\Anaconda3\envs\python36\lib\site-packages\rest_framework\reverse.py" in _reverse 60. url = django_reverse(viewname, args=args, kwargs=kwargs, **extra)
File "C:\Anaconda3\envs\python36\lib\site-packages\django\urls\base.py" in reverse 90. return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "C:\Anaconda3\envs\python36\lib\site-packages\django\urls\resolvers.py" in _reverse_with_prefix 622. raise NoReverseMatch(msg)
Exception Type: NoReverseMatch at / Exception Value: Reverse for 'user-list' not found. 'user-list' is not a valid view function or pattern name.
Another url.py file is
from django.contrib import admin
from django.urls import path
from django.urls import include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('snippets.urls'))
]
Project structure
tutorials
|_snippets
| |_urls.py
| |_views.py
| |_models.py
| |_apps.py
| |_admin.py
|_tutorials
|_urls.py
|_settings.py
|_wsgi.py
reverse only accept these parameter:
reverse(viewname, urlconf=None, args=None, kwargs=None,
current_app=None)
and your users/ doesn't accept any arguments so you only need the url name in reverse
reverse('user-list')

Django Unknown field(s) (username) specified for PoUser

I got this error because I create a custom usermodel, and When I got all setup, which I look into the django/contrib/auth/models.py, I set the email as USERNAME_FIELD, and REQUIRED_FIELD is some field that is not defined in AbstractBaseUser and PermissionMixin which my UserModel inherited, I can access all section except the 'Po User add section', and I put on my codes in models.py and admin.py and settings.py ,urls.py ,wish somebody could help.
error traces:
Unknown field(s) (username) specified for PoUser
Request Method: GET
Request URL: http://127.0.0.1/newproject/admin/Testsite/pouser/add/
Django Version: 1.5.1
Exception Type: FieldError
Exception Value:
Unknown field(s) (username) specified for PoUser
Exception Location: /usr/local/lib/python2.7/dist-packages/django/forms/models.py in __new__, line 221
Python Executable: /usr/bin/python
Python Version: 2.7.3
/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in get_response
response = callback(request, *callback_args, **callback_kwargs) ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs) ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py in _wrapped_view
response = view_func(request, *args, **kwargs) ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/django/views/decorators/cache.py in _wrapped_view_func
response = view_func(request, *args, **kwargs) ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/django/contrib/admin/sites.py in inner
return view(request, *args, **kwargs) ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/django/views/decorators/debug.py in sensitive_post_parameters_wrapper
return view(request, *args, **kwargs) ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py in _wrapper
return bound_func(*args, **kwargs) ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py in _wrapped_view
response = view_func(request, *args, **kwargs) ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py in bound_func
return func(self, *args2, **kwargs2) ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/django/db/transaction.py in inner
return func(*args, **kwargs) ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/django/contrib/auth/admin.py in add_view
extra_context) ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py in _wrapper
return bound_func(*args, **kwargs) ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py in _wrapped_view
response = view_func(request, *args, **kwargs) ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py in bound_func
return func(self, *args2, **kwargs2) ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/django/db/transaction.py in inner
return func(*args, **kwargs) ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py in add_view
ModelForm = self.get_form(request) ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/django/contrib/auth/admin.py in get_form
return super(UserAdmin, self).get_form(request, obj, **defaults) ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py in get_form
return modelform_factory(self.model, **defaults) ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/django/forms/models.py in modelform_factory
return type(form)(class_name, (form,), form_class_attrs) ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/django/forms/models.py in __new__
raise FieldError(message) ...
models.py
from django.db import models
from django.contrib.auth.models import Group
from django.utils import timezone
from django.contrib.auth.models import BaseUserManager,AbstractBaseUser,PermissionsMixin
from django.db import models
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from django import forms
from django.contrib import admin
from taggit.managers import TaggableManager
from django.core.exceptions import ValidationError
from django.forms import ModelForm
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
# Create your models here.
class poUserManager(BaseUserManager):
def create_user(self,email,password=None,first_name=None,last_name=None,last_login=None,date_join=None):
now=timezone.now()
if not email:
raise ValueError("The given email must be setted")
user = self.model(email=self.normalize_email(email),is_staff=True, is_active=True, is_superuser=False,last_login=now, date_join=date_join,first_name=first_name,last_name=last_name)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self,email,password,first_name,last_name,last_login,date_join):
now=timezone.now()
u=self.create_user(email,password,first_name=first_name,last_name=last_name,date_join=date_join)
u.is_staff=True
u.active=True
u.is_superuser=True
u.save(using=self.db)
return u
##python_2_unicode_compatible
class PoUser(AbstractBaseUser,PermissionsMixin):
email=models.EmailField(verbose_name='email address',max_length=255,unique=True,db_index=True)
first_name=models.CharField(max_length=30)
last_name=models.CharField(max_length=20)
date_join=models.DateField(default=timezone.now)
is_staff = models.BooleanField(_('staff status'), default=False,help_text=_('Designates whether the user can log into this admin ''site.'))
is_active = models.BooleanField(_('active'), default=True,help_text=_('Designates whether this user should be treated as ''active. Unselect this instead of deleting accounts.'))
is_admin=models.BooleanField(default=False)
USERNAME_FIELD='email'
#REQUIRED_FIELD=['first_name','last_name','date_join','is_active','is_admin','groups','user_permissions','is_superuser','last_login','is_staff']
REQUIRED_FIELD=['last_name','first_name','date_join']
objects=poUserManager()
def get_full_name(self):
return self.firstname
def get_short_name(self):
return self.first_name
# def has_perm(self,perm,obj):
# if self.is_active and self.is_superuser:
# return True
# return this.groups.values_list(self.email,flat=True)
# return _user_has_perm(self,perm.obj)
def __unicode__(self):
return self.email
def get_group(self):
return self.objects.values('groups')
admin.py:
from django.db import models
from django.contrib.auth.models import Group
from django.utils import timezone
from django.contrib.auth.models import BaseUserManager,AbstractBaseUser,PermissionsMixin
from django.db import models
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from django import forms
from Testsite.models import PoUser
from django.contrib import admin
from taggit.managers import TaggableManager
from django.core.exceptions import ValidationError
from django.forms import ModelForm
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.admin import GroupAdmin
from django.contrib import admin
class UserCreationForm(forms.ModelForm):
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = PoUser
fields = ('email','first_name','last_name','groups','user_permissions','date_join','is_staff','is_active','is_admin',)
#fields=('email','first_name','last_name')
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self,commit=True):
user=super(UserCreationForm,self).save(commit=False)
user.set_password(self.clean_data['password1'])
if commit:
user.save()
return user
class UserChangeForm(forms.ModelForm):
password=ReadOnlyPasswordHashField()
class Meta:
model = PoUser
fields=['email','first_name','last_name','groups','user_permissions','date_join','is_staff','is_active','is_admin']
def clean_password(self):
return self.initial["password"]
class MyUserAdmin(UserAdmin):
form=UserChangeForm
add_form=UserCreationForm
#fields=('email','first_name','last_name','groups','user_permissions','date_join','is_staff','is_admin')
list_display = ('email','first_name','last_name')
list_filter=('is_admin',)
search_fields = ('email','first_name','last_name')
ordering = ('email',)
fieldsets = ((None, {'fields': ('email', 'password')}),('Personal info', {'fields': ('last_name','groups','date_join')}),('Permissions', {'fields': ('is_admin','is_staff')}),)
admin.site.register(PoUser, MyUserAdmin)
settings.py:
ADMIN_MEDIA_PREFIX='/admin_media/'
AUTH_USER_MODEL = 'Testsite.PoUser'
The parent class (django.contrib.auth.admin.UserAdmin) has an add_fieldsets attribute that includes the username field. Add an attribute to your MyUserAdmin class called add_fieldsets and treat it like the fieldsets attribute: use it to define fields you want to show in the add form.
Note: If your username is set to email then add email to add_fieldsets.
See the note about add_fieldset at the "Customizing authentication in Django" docs page and the full example from the Django docs.
Add the add_fieldsets attribute to your adminModel class like below
from django.contrib.auth.admin import UserAdmin
class CustomUserAdmin(UserAdmin):
...
# add fields those needs to be visible while adding the data in form.
add_fieldsets = (
(None, {'fields': ('first_name', 'last_name', 'email', 'password', 'role', 'country_code', 'country',
'is_active', 'verified')}),
)
...
more information can be found here. https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#custom-users-and-django-contrib-admin