OperationalError at /register/ no such table: users_customuser

I have no idea why I’m getting this error?

models.py


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


from .managers import CustomUserManager


class CustomUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    date_joined = models.DateTimeField(default=timezone.now)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = CustomUserManager()

    def __str__(self):
        return self.email

managers.py


from django.contrib.auth.base_user import BaseUserManager
from django.utils.translation import gettext_lazy as _



class CustomUserManager(BaseUserManager):
    """
    Custom user model manager where email is the unique identifiers
    for authentication instead of usernames.
    """
    def create_user(self, email, password, **extra_fields):
        """
        Create and save a User with the given email and password.
        """
        if not email:
            raise ValueError(_('The Email must be set'))
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, email, password, **extra_fields):
        """
        Create and save a SuperUser with the given email and password.
        """
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_active', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError(_('Superuser must have is_staff=True.'))
        if extra_fields.get('is_superuser') is not True:
            raise ValueError(_('Superuser must have is_superuser=True.'))
        return self.create_user(email, password, **extra_fields)

forms.py


from django.contrib.auth.forms import UserCreationForm, UserChangeForm

from .models import CustomUser


class CustomUserCreationForm(UserCreationForm):

    class Meta:
        model = CustomUser
        fields = ('email',)


class CustomUserChangeForm(UserChangeForm):

    class Meta:
        model = CustomUser
        fields = ('email',)

error message:


|Request Method:|POST|
| --- | --- |
|Request URL:|http://127.0.0.1:8000/register/|
|Django Version:|4.0|
|Exception Type:|OperationalError|
|Exception Value:|no such table: users_customuser|
|Exception Location:|C:\Users\zesha\Documents\GitHub\sust-cse-alumni-repo\iftu\lib\site-packages\django\db\backends\sqlite3\base.py, line 416, in execute|
|Python Executable:|C:\Users\zesha\Documents\GitHub\sust-cse-alumni-repo\iftu\Scripts\python.exe|
|Python Version:|3.9.9|
|Python Path:|['C:\\Users\\zesha\\Documents\\GitHub\\sust-cse-alumni-repo', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\\python39.zip', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\\DLLs', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\\lib', 'C:\\Users\\zesha\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0', 'C:\\Users\\zesha\\Documents\\GitHub\\sust-cse-alumni-repo\\iftu', 'C:\\Users\\zesha\\Documents\\GitHub\\sust-cse-alumni-repo\\iftu\\lib\\site-packages']|
|Server time:|Fri, 10 Dec 2021 22:18:51 +0000|

Help me please!

  1. Have you done a “makemigrations” / “migrate” for this app? (Or, if not, have you created these tables?)

  2. Have you made the appropriate settings change to use this CustomUser?

  3. Is the name of the app in which this CustomUser resides named “users”?

  4. Can you post the output of a “showmigrations”?

1 Like

Ans of your question.

  1. I’ve done them.
  2. Help me do it.
  3. Yes it’s users.
  4. Show migrations:

[X] 0005_alter_user_last_login_null
 [X] 0006_require_contenttypes_0002
 [X] 0007_alter_validators_add_error_messages
 [X] 0008_alter_user_username_max_length
 [X] 0009_alter_user_last_name_max_length
 [X] 0010_alter_group_name_max_length
 [X] 0011_update_proxy_permissions
 [X] 0012_alter_user_first_name_max_length
contenttypes
 [X] 0001_initial
 [X] 0002_remove_content_type_name
sessions
 [X] 0001_initial

To answer your question, see Substituting a custom User model and the AUTH_USER_MODEL setting.

Something’s out of sync. Since you’re using Sqlite as the database, I’d suggest trying it from scratch. Change the database to a different file, migrate, and verify that the table has been created in the database. If that works, check your current database to see if that table exists. If it doesn’t, then that table got dropped somehow. (No way to tell how.)

views.py

from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import CustomUserCreationForm

def register(request):
    if request.method == 'POST':
        form = CustomUserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            email = form.cleaned_data.get('email')
            messages.success(
                request, "Your account has been created! Your ar now able to login.")
            return redirect('login')
    else:
        form = CustomUserCreationForm()
    return render(request, 'users/register.html', {'form': form})


@login_required
def profile(request):
    if request.method == 'POST':
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = ProfileUpdateForm(
            request.POST, request.FILES, instance=request.user.profile)

        if u_form.is_valid() and p_form.is_valid():
            u_form.save()
            p_form.save()
            messages.success(request, "Your account has been updated!")
            return redirect('profile')

    else:
        u_form = UserUpdateForm(instance=request.user)
        p_form = ProfileUpdateForm(instance=request.user.profile)

    context = {
        'u_form': u_form,
        'p_form': p_form
    }
    return render(request, 'users/profile.html', context)

Is there any problem with my views.py flle?

So you’ve verified your database and can see the table in it?

Yes, it’s possible that you have errors in your view - but none are going to generate that error.

1 Like

Thanks I accidentally deleted my migrations folder.
Then I created it and created a file named init.py inside it.
Deleted the db.sqlite
then did all the makemigrations and migrate.
It worked for me.

From seeing all the other problems you’ve reported, I was starting to get the impression that you had mistakenly deleted one or more migration files. Glad to see you’ve gotten it working.
Be aware - you do not want to delete any migration files, unless you’re going to delete all of them. (And even then you want to be careful doing that.)