Facing error in inbuilt login function of django

hy guys i created a custom user model in django it is registering the user but when i try to login it gives me following error .

Cannot force an update in save() with no primary key.

can you address me how to solve it or what is going wrong…?

We’ll need to see the custom user model, how you’re doing the “registering” of users, and the view that is throwing the error. It would also be helpful if you posted (copy/paste, not image) the complete traceback of the error you’re receiving.

When posting code here (or templates, or error messages), enclose it between lines of three backtick characters. This means you’ll have a line of ```, then your code, then another line of ```. This forces the forum software to keep your code properly formatted, which is critical with Python.

Here is my code for customer user model
“”"
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager,PermissionsMixin
from django.utils.translation import gettext_lazy as _
from django.utils import timezone

Create your models here.

class UserAccountManager(BaseUserManager):
def _create_user(self,username, email, password, **extra_fields):
email = self.normalize_email(email)
user = self.model(email=email,username=username,password=password, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user

def create_user(self, email,username, password, **extra_fields):
	extra_fields.setdefault('is_staff', False)
	extra_fields.setdefault('is_superuser', False)
	extra_fields.setdefault('is_active', True)
	return self._create_user(username,email, password, **extra_fields)

def create_staff_user(self, email,username, password, **extra_fields):
	extra_fields.setdefault('is_staff', True)
	extra_fields.setdefault('is_superuser', False)
	extra_fields.setdefault('is_active', True)
	return self._create_user(username,email, password, **extra_fields)

def create_superuser(self, email,username, password, **extra_fields):
	extra_fields.setdefault('is_staff', True)
	extra_fields.setdefault('is_superuser', True)
	extra_fields.setdefault('is_active', True)
	return self._create_user(username,email, password, **extra_fields)

class CustomUser(AbstractBaseUser, PermissionsMixin):
first_name = models.CharField((‘First name’), max_length=30, blank=True)
last_name = models.CharField(
(‘Last name’), max_length=30, blank=True)
email = models.EmailField((‘Email address’), unique=True)
username = models.CharField(max_length=200,unique=True)
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=False, help_text=(
‘Designates whether this user should be treated as active.’), )
date_joined = models.DateTimeField(
(‘Date joined’), default=timezone.now)
user_role = models.CharField(max_length=200,blank=True)
objects = UserAccountManager()
USERNAME_FIELD = ‘username’
REQUIRED_FIELDS = [‘first_name’, ‘last_name’,‘email’]

class Meta:
	verbose_name = _('User')
	verbose_name_plural = _('User')
	ordering = ('-pk',)

def __str__(self):
	return self.email


def has_perm(self, perm, obj=None):
	return True

def has_module_perms(self, app_label):
	return True

def get_full_name(self):
	"""
	Returns the first_name plus the last_name, with a space in between.
	"""
	full_name = "{} {}".format(self.first_name, self.last_name)
	return full_name.strip()

def get_short_name(self):
	return self.first_name.strip()

“”"
I am not getting any kind of error while creating a superuser

Note: You need to surround the code with three backtick - ` characters, not apostrophes - ’ or double-quotes - ".

How are the users getting created?

i just added the code and created one superuser and then in login i am facing this error

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager,PermissionsMixin
from django.utils.translation import gettext_lazy as _
from django.utils import timezone

# Create your models here.

class UserAccountManager(BaseUserManager):
	def _create_user(self,username, email, password, **extra_fields):
		email = self.normalize_email(email)
		user = self.model(email=email,username=username,password=password, **extra_fields)
		user.set_password(password)
		user.save(using=self._db)
		return user

	def create_user(self, email,username, password, **extra_fields):
		extra_fields.setdefault('is_staff', False)
		extra_fields.setdefault('is_superuser', False)
		extra_fields.setdefault('is_active', True)
		return self._create_user(username,email, password, **extra_fields)

	def create_staff_user(self, email,username, password, **extra_fields):
		extra_fields.setdefault('is_staff', True)
		extra_fields.setdefault('is_superuser', False)
		extra_fields.setdefault('is_active', True)
		return self._create_user(username,email, password, **extra_fields)

	def create_superuser(self, email,username, password, **extra_fields):
		extra_fields.setdefault('is_staff', True)
		extra_fields.setdefault('is_superuser', True)
		extra_fields.setdefault('is_active', True)
		return self._create_user(username,email, password, **extra_fields)


class CustomUser(AbstractBaseUser, PermissionsMixin):
	first_name = models.CharField(_('First name'), max_length=30, blank=True)
	last_name = models.CharField(_('Last name'), max_length=30, blank=True)
	email = models.EmailField(_('Email address'), unique=True)
	username = models.CharField(max_length=200,unique=True)
	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=False, help_text=_(
		'Designates whether this user should be treated as active.'), )
	date_joined = models.DateTimeField(_('Date joined'), default=timezone.now)
	user_role = models.CharField(max_length=200,blank=True)
	objects = UserAccountManager()
	USERNAME_FIELD = 'username'
	REQUIRED_FIELDS = ['first_name', 'last_name','email']
	
	class Meta:
		verbose_name = _('User')
		verbose_name_plural = _('User')
		ordering = ('-pk',)

	def __str__(self):
		return self.email


	def has_perm(self, perm, obj=None):
		return True

	def has_module_perms(self, app_label):
		return True

	def get_full_name(self):
		"""
		Returns the first_name plus the last_name, with a space in between.
		"""
		full_name = "{} {}".format(self.first_name, self.last_name)
		return full_name.strip()

	def get_short_name(self):
		return self.first_name.strip()

How are you logging in? Are you using the default login view? Are you using a custom template? Where are users being redirected to after logging in?

Please post the complete traceback of the error from your console.

def my_view(request):
	try:
		username = request.POST['username']
		password = request.POST['password']
		try:
			user = authenticate(username=username, password=password)
		except Exception as e:
			print("error in authentication ::: ",e)
		if user is not None:
			request.user.user_role = user.user_role
			user_permissions = handle_section_permissions_for_sidebar(request)
			if user.is_active and user.is_authenticated:
				try:
					print("user :::::::",user)
					login(request, user)
				except Exception as e:
					print(">>>>>>>>  login error  >>>>>>>>>>>>>>",e)
				if "Dashboard" in user_permissions or ("all" in user_permissions):
					return HttpResponseRedirect("/dashboard")
				else:
					return HttpResponseRedirect('/change-password') 
			# Return an 'invalid login' error message.
	except Exception as e:
		print("error in my_view :::::::::::",e)
	return HttpResponseRedirect("/dashboard")

This how my login functionality works

from django.contrib.auth import authenticate, login

using this login function

>>>>>>>>  login error  >>>>>>>>>>>>>> Cannot force an update in save() with no primary key.
[07/Jun/2022 17:25:52] "POST /account/login/ HTTP/1.1" 302 0
Internal Server Error: /change-password
Traceback (most recent call last):
  File "C:\Users\gabba\Desktop\Geeker\env\lib\site-packages\django\db\models\fields\__init__.py", line 1836, in to_python
    return int(value)
ValueError: invalid literal for int() with base 10: 'None'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\gabba\Desktop\Geeker\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\gabba\Desktop\Geeker\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\gabba\Desktop\Geeker\env\lib\site-packages\django\contrib\auth\decorators.py", line 20, in _wrapped_view
    if test_func(request.user):
  File "C:\Users\gabba\Desktop\Geeker\env\lib\site-packages\django\contrib\auth\decorators.py", line 44, in <lambda>
    lambda u: u.is_authenticated,
  File "C:\Users\gabba\Desktop\Geeker\env\lib\site-packages\django\utils\functional.py", line 246, in inner
    self._setup()
  File "C:\Users\gabba\Desktop\Geeker\env\lib\site-packages\django\utils\functional.py", line 382, in _setup
    self._wrapped = self._setupfunc()
  File "C:\Users\gabba\Desktop\Geeker\env\lib\site-packages\django\contrib\auth\middleware.py", line 23, in <lambda>
    request.user = SimpleLazyObject(lambda: get_user(request))
  File "C:\Users\gabba\Desktop\Geeker\env\lib\site-packages\django\contrib\auth\middleware.py", line 11, in get_user
    request._cached_user = auth.get_user(request)
  File "C:\Users\gabba\Desktop\Geeker\env\lib\site-packages\django\contrib\auth\__init__.py", line 177, in get_user
    user_id = _get_user_session_key(request)
  File "C:\Users\gabba\Desktop\Geeker\env\lib\site-packages\django\contrib\auth\__init__.py", line 60, in _get_user_session_key
    return get_user_model()._meta.pk.to_python(request.session[SESSION_KEY])
  File "C:\Users\gabba\Desktop\Geeker\env\lib\site-packages\django\db\models\fields\__init__.py", line 1838, in to_python
    raise exceptions.ValidationError(
django.core.exceptions.ValidationError: ['“None” value must be an integer.']
[07/Jun/2022 17:25:52] "GET /change-password HTTP/1.1" 500 104682

This is full error from console

The error is being thrown at that url. I see where you’re redirecting to that in your inner if condition - neither “Dashboard” nor “all” are in user_permissions.

However, getting to that point indicates that you are authenticating. (Both user.is_active and user.is_authenticated are true - otherwise you wouldn’t reach the inner if.)

What view handles that url? (/change-password)

i checked that error if says the user is None in request.user but according to django login functions user should be set in request.user after login is successfull

Ok, I see what’s happening here so far. (I missed that the exception was being caught before the redirect.)

How did you create your superuser? (Did you use the management command createsuperuser?)

Are you using only the “default” middleware in the order they’re normally provided?
Do you have ‘django.contrib.auth’ in INSTALLED_APPS?
Are you using any special or additional AUTHENTICATION_BACKEND entries?

And a follow-on question - do you have any listeners set up for the user_logged_in signal?

It might actually be more useful if you removed your exception handler with that print statement, allowing Django to give you a full traceback at the location where the error is occurring. (Or print the full traceback at that point.)

  • I am using createsuperuser command

  • yes i am using default middleware django provided

  • yes django.contrib.auth is in my installed APPS

  • i am using a variable AUTH_USER_MODEL = ‘accounts.CustomUser’ in my django settings.py only

user logged in callback is not working because there user is not getting logged in

We do not know that, because the signal methods are called in the login method and you’re not showing the full traceback from the original error.

It’s possible that the root cause of this exception is in the signal handler and the exception being thrown is caught by your exception handler - but it’s not possible to determine whether or not that’s what’s happening without seeing the traceback of the original exception.