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

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

Related

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

Django login method gives recursion error

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)

Manager isn't available; 'auth.User' has been swapped for 'members.CustomUser'

i have problem with my code when i want signup error appear Manager isn't available; 'auth.User' has been swapped for 'members.CustomUser' , i try solotion of other questions same like Manager isn't available; 'auth.User' has been swapped for 'members.CustomUser' but all of them asking to replace User = User = get_user_model() but i am not use any User in my code or i dont know where i used that.im new in django , python , js and etc so if my question is silly forgivme .
for more information :1) i used Django Signup Tutorial for create signup method . first that was working well but after i expand my homework project i get error .2)in others app ("products" and "search") no where im not import User and even i dont use CustomUser too bez not need to work with User in this apps.just memebers work with User and CustomUser.
model.py :
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
def __str__(self):
return self.email
class Meta:
verbose_name = "member"
verbose_name_plural = "members"
setting.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'card.apps.CardConfig',
'members.apps.MembersConfig',
'search.apps.SearchConfig',
'products.apps.ProductsConfig',
'rest_framework',
]
AUTH_USER_MODEL = 'members.CustomUser'
admin.py:
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import CustomUser
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = CustomUser
list_display = ['email', 'username']
admin.site.register(CustomUser, CustomUserAdmin)
form.py:
# users/forms.py
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = CustomUser
fields = ('username', 'email')
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = CustomUser
fields = ('username', 'email')
error:
27/Feb/2019 12:36:01] "GET /signup/ HTTP/1.1" 200 5293
Internal Server Error: /signup/
Traceback (most recent call last):
File "C:\shopping\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\shopping\venv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\shopping\venv\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\shopping\venv\lib\site-packages\django\views\generic\base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "C:\shopping\venv\lib\site-packages\django\views\generic\base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "C:\shopping\venv\lib\site-packages\django\views\generic\edit.py", line 172, in post
return super().post(request, *args, **kwargs)
File "C:\shopping\venv\lib\site-packages\django\views\generic\edit.py", line 141, in post
if form.is_valid():
File "C:\shopping\venv\lib\site-packages\django\forms\forms.py", line 185, in is_valid
return self.is_bound and not self.errors
File "C:\shopping\venv\lib\site-packages\django\forms\forms.py", line 180, in errors
self.full_clean()
File "C:\shopping\venv\lib\site-packages\django\forms\forms.py", line 383, in full_clean
self._post_clean()
File "C:\shopping\venv\lib\site-packages\django\contrib\auth\forms.py", line 107, in _post_clean
super()._post_clean()
File "C:\shopping\venv\lib\site-packages\django\forms\models.py", line 403, in _post_clean
self.instance.full_clean(exclude=exclude, validate_unique=False)
File "C:\shopping\venv\lib\site-packages\django\db\models\base.py", line 1137, in full_clean
self.clean()
File "C:\shopping\venv\lib\site-packages\django\contrib\auth\models.py", line 338, in clean
self.email = self.__class__.objects.normalize_email(self.email)
File "C:\shopping\venv\lib\site-packages\django\db\models\manager.py", line 188, in __get__
cls._meta.swapped,
AttributeError: Manager isn't available; 'auth.User' has been swapped for 'members.CustomUser'
[27/Feb/2019 12:36:04] "POST /signup/ HTTP/1.1" 500 113770
Modify views.py
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
from django.views import generic
class SignUp(generic.CreateView):
form_class = UserCreationForm
success_url = reverse_lazy('login')
template_name = 'signup.html'
to
from .forms import CustomUserCreationForm
from django.urls import reverse_lazy
from django.views import generic
class SignUp(generic.CreateView):
form_class = CustomUserCreationForm
success_url = reverse_lazy('login')
template_name = 'signup.html'
In your forms.py make changes as:
from django.contrib.auth import get_user_model
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = get_user_model()
fields = ('username', 'email')
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = get_user_model()
fields = ('username', 'email')
Also add this script in your members/init.py file:
default_app_config = 'members.apps.MembersConfig'

'NoneType' object has no attribute '_meta'

I am trying to build register api. Here i am stuck with the problem and hoping you guys will address my mistake and will lead me to right way. Anyway thanks in advance. Hoping for your soon response. Thank you .
serializers.py
from django.contrib.auth.models import User
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email', 'password')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
""" Create and return a new user"""
user = User.objects.create_user(**validated_data)
return user
models.py
from django.db import models
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.models import BaseUserManager
from django.contrib.auth import get_user_model
class UserRegisterManager(BaseUserManager):
""" Helps django work with our custom user model """
def createUser(self, email, name, password=None):
""" Creates a new user profile object """
if not email:
raise ValueError("User must have an email address.")
email = self.normalize_email(email)
user = self.model(email=email, name=name)
user.set_password(password) # set_password helps to convert str into hash
user.save(using=self._db)
return user
def create_superuser(self, email, name, password):
""" Creates and saves a new superuser with given details. """
user = self.create_user(email, name, password)
user.is_superuser = True
user.is_staff = True
user.save(using=self._db)
return user
class UserRegister(AbstractBaseUser, PermissionsMixin):
""" Represents a 'user register' inside our system """
email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255)
is_active = models.BooleanField(default=True) # user is currently active or not
is_staff = models.BooleanField(default=False)
objects = UserRegisterManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name']
def get_full_name(self):
""" Used to get user fullname """
return self.name
def get_short_name(self):
""" Used to get user short name """
return self.name
def __str__(self):
""" Django uses this when it need to convert the object to a string """
return self.email
this is my model
views.py
from django.contrib.auth.models import User
from rest_framework import viewsets
from rest_framework.authentication import TokenAuthentication
from .serializers import UserSerializer
from . import permissions
from django.contrib.auth import get_user_model
User = get_user_model()
class UserViewSet(viewsets.ModelViewSet):
""" API endpoint that allows users to be viewed or edited. """
serializer_class = UserSerializer
queryset = User.objects.all()
# authentication_classes = (TokenAuthentication,)
# permission_classes = (permissions.UpdateProfile,)
setting.py
AUTH_USER_MODEL = 'register.UserRegister'
this helps to switch to costume user.
admin.py
from django.contrib import admin
from .models import UserRegister
admin.site.register(UserRegister)
And this is how i register my model
Error
This is error
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/api/register/
Django Version: 2.1.5
Python Version: 3.7.1
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'register',
'corsheaders']
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',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware']
Traceback:
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\django\core\handlers\base.py" in _get_response
156. response = self.process_exception_by_middleware(e, request)
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\django\core\handlers\base.py" in _get_response
154. response = response.render()
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\django\template\response.py" in render
106. self.content = self.rendered_content
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\response.py" in rendered_content
72. ret = renderer.render(self.data, accepted_media_type, context)
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\renderers.py" in render
733. context = self.get_context(data, accepted_media_type, renderer_context)
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\renderers.py" in get_context
663. raw_data_post_form = self.get_raw_data_form(data, view, 'POST', request)
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\renderers.py" in get_raw_data_form
574. data = serializer.data.copy()
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\serializers.py" in data
563. ret = super(Serializer, self).data
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\serializers.py" in data
266. self._data = self.get_initial()
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\serializers.py" in get_initial
413. for field in self.fields.values()
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\serializers.py" in fields
363. for key, value in self.get_fields().items():
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\serializers.py" in get_fields
1024. info = model_meta.get_field_info(model)
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\utils\model_meta.py" in get_field_info
39. forward_relations = _get_forward_relationships(opts)
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\utils\model_meta.py" in _get_forward_relationships
96. not field.remote_field.through._meta.auto_created
Exception Type: AttributeError at /api/register/
Exception Value: 'NoneType' object has no attribute '_meta'
from django.contrib.auth import get_user_model
User = get_user_model()
Always use that to access the user model instead of this
from django.contrib.auth.models import User
to account for custom user models.

Keeping custom sign_up class and importing allauth forms in same forms.py file causing import errors

from django import forms
from allauth.account.forms import (LoginForm, ChangePasswordForm,
ResetPasswordForm, SetPasswordForm, ResetPasswordKeyForm)
from django.contrib.auth import get_user_model
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div, Submit, HTML, Button, Row, Field
from crispy_forms.bootstrap import AppendedText, PrependedText, FormActions
from django.core.urlresolvers import reverse
class MySignupForm(forms.Form):
class Meta:
model = get_user_model()
fields = ['email', 'first_name', 'last_name']
def __init__(self, *args, **kwargs):
super(MySignupForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.fields["email"].widget.input_type = "email" # ugly hack
self.helper.form_method = "POST"
self.helper.form_action = "account_signup"
self.helper.form_id = "signup_form"
self.helper.form_class = "signup"
self.helper.layout = Layout(
Field('email', placeholder="Enter Email", autofocus=""),
Field('first_name', placeholder="Enter First Name"),
Field('last_name', placeholder="Enter Last Name"),
Field('password1', placeholder="Enter Password"),
Field('password2', placeholder="Re-enter Password"),
Submit('sign_up', 'Sign up', css_class="btn-warning"),
)
def signup(self, request, user):
pass
class MyLoginForm(LoginForm):
remember_me = forms.BooleanField(required=False, initial=False)
def __init__(self, *args, **kwargs):
super(MyLoginForm, self).__init__(*args, **kwargs)
class MyPasswordChangeForm(ChangePasswordForm):
def __init__(self, *args, **kwargs):
super(MyPasswordChangeForm, self).__init__(*args, **kwargs)
I have structure like this in my app.forms.py file, where i am importing allauth built in forms LoginForm ResetPasswordForm etc. and in the same file i am defining custom signup class.
hook for custom signup class:
ACCOUNT_SIGNUP_FORM_CLASS = 'allauth_core.forms.MySignupForm'
I think i am hitting circular import issue but not sure why ?
File "/Users/rmahamuni/.virtualenvs/todo/lib/python2.7/site-packages/allauth/urls.py", line 8, in
urlpatterns = [url('^', include('allauth.account.urls'))]
File "/Users/rmahamuni/.virtualenvs/todo/lib/python2.7/site-packages/django/conf/urls/init.py", line 52, in include
urlconf_module = import_module(urlconf_module)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/init.py", line 37, in import_module
import(name)
File "/Users/rmahamuni/.virtualenvs/todo/lib/python2.7/site-packages/allauth/account/urls.py", line 4, in
from . import views
File "/Users/rmahamuni/.virtualenvs/todo/lib/python2.7/site-packages/allauth/account/views.py", line 19, in
from .forms import (
File "/Users/rmahamuni/.virtualenvs/todo/lib/python2.7/site-packages/allauth/account/forms.py", line 206, in
class BaseSignupForm(_base_signup_form_class()):
File "/Users/rmahamuni/.virtualenvs/todo/lib/python2.7/site-packages/allauth/account/forms.py", line 188, in _base_signup_form_class
' "%s"' % (fc_module, e))
django.core.exceptions.ImproperlyConfigured: Error importing form class allauth_core.forms: "cannot import name ChangePasswordForm"
If i keep custom signup form in separate file then i dont get this issue.
I tried switching installed apps lineup
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth_core', <-- app where form is located.
What am i missing here ? can someone please guide me ? Thanks
This happens because allauth tries to import the given module/class you specified as signup form in your settings.py in its account/forms.py. (See forms.py#L186 # github)
When you override other forms like ChangePasswordForm in your settings.py by importing allauth's account/forms.py, circular import happens because allauth has already imported your forms.py in its forms.py
To avoid this, simply move your singup form to a separate signupform.py and change the settings accordingly. It'll work.