VATSAL JAIN
VATSAL JAIN

Reputation: 581

Getting this error: ProgrammingError at /admin/ relation "myapp_myuser" does not exist while creating superuser or going on localhost/admin

I tried extending the user model in django with the help of django docs.I wanted to add a mobile field to it.I did everything and then even executed makemigrations , sqlmigrate and migrate and got no error but when i try to execute python manage.py createsuperuser i get a response asking for email and as soon as it enter email i get this error

I havent made a separate app for this model and am using the same models.py for the whole project The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\contrib\admin\sites.py", line 249, in wrapper
    return self.admin_view(view, cacheable)(*args, **kwargs)
  File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\contrib\admin\sites.py", line 220, in inner
    if not self.has_permission(request):
  File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\contrib\admin\sites.py", line 194, in has_permission
    return request.user.is_active and request.user.is_staff
  File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\utils\functional.py", line 224, in inner
    self._setup()
  File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\utils\functional.py", line 360, in _setup
    self._wrapped = self._setupfunc()
  File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\contrib\auth\middleware.py", line 24, in <lambda>
    request.user = SimpleLazyObject(lambda: get_user(request))
  File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\contrib\auth\middleware.py", line 12, in get_user
    request._cached_user = auth.get_user(request)
  File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\contrib\auth\__init__.py", line 180, in get_user
    user = backend.get_user(user_id)
  File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\contrib\auth\backends.py", line 161, in get_user
    user = UserModel._default_manager.get(pk=user_id)
  File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\db\models\query.py", line 411, in get
    num = len(clone)
  File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\db\models\query.py", line 258, in __len__
    self._fetch_all()
  File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\db\models\query.py", line 1261, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\db\models\query.py", line 57, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\db\models\sql\compiler.py", line 1152, in execute_sql
    cursor.execute(sql, params)
  File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\db\backends\utils.py", line 100, in execute
    return super().execute(sql, params)
  File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\db\backends\utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\db\utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation " myapp_myuser" does not exist
LINE 1: ...er"."is_active", " myapp_myuser"."is_admin" FROM " myapp_m...

Here is my code: models.py

from django.db import models
from datetime import datetime
from django.utils import timezone
from django.contrib.auth.models import User,auth
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)


class MyUserManager(BaseUserManager):
    def create_user(self, email, mobile, password=None):
        """
        Creates and saves a User with the given email, date of
        birth and password.
        """
        if not email:
            raise ValueError('Users must have an email address')
        if not mobile:
            raise ValueError('Users must have a mobile number')

        user = self.model(
            email=self.normalize_email(email),
            mobile=mobile,
        )

        user.set_password(password)
        user.save(using=self._db)
        return user
    
    def create_superuser(self, email, mobile, password=None):
        """
        Creates and saves a superuser with the given email, date of
        birth and password.
        """
        user = self.create_user(
            email,
            password=password,
            mobile=mobile,
        )
        user.is_admin = True
        user.save(using=self._db)
        return user


class MyUser(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    mobile = models.CharField(max_length=12)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = MyUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['mobile']

    def __str__(self):
        return self.email




    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_admin

admin.py

from django.contrib import admin
from . models import Category,Product,MyUser
from django import forms
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField



class UserCreationForm(forms.ModelForm):
    """A form for creating new users. Includes all the required
    fields, plus a repeated password."""
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)

    class Meta:
        model = MyUser
        fields = ('email', 'mobile')

    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):
        # Save the provided password in hashed format
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user


class UserChangeForm(forms.ModelForm):
    """A form for updating users. Includes all the fields on
    the user, but replaces the password field with admin's
    password hash display field.
    """
    password = ReadOnlyPasswordHashField()

    class Meta:
        model = MyUser
        fields = ('email', 'password', 'mobile', 'is_active', 'is_admin')

    def clean_password(self):
        # Regardless of what the user provides, return the initial value.
        # This is done here, rather than on the field, because the
        # field does not have access to the initial value
        return self.initial["password"]


class UserAdmin(BaseUserAdmin):
    # The forms to add and change user instances
    form = UserChangeForm
    add_form = UserCreationForm

    # The fields to be used in displaying the User model.
    # These override the definitions on the base UserAdmin
    # that reference specific fields on auth.User.
    list_display = ('email', 'mobile', 'is_admin')
    list_filter = ('is_admin',)
    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('Personal info', {'fields': ('mobile',)}),
        ('Permissions', {'fields': ('is_admin',)}),
    )
    # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
    # overrides get_fieldsets to use this attribute when creating a user.
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'mobile', 'password1', 'password2'),
        }),
    )
    search_fields = ('email',)
    ordering = ('email',)
    filter_horizontal = ()



admin.site.register(MyUser, UserAdmin)

admin.site.unregister(Group)

admin.site.register(Category)
admin.site.register(Product)

settings.py

AUTH_USER_MODEL = 'myapp.MyUser'
# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp.apps.MyappConfig'
]

Please tell me how to solve the error.

Upvotes: 1

Views: 1861

Answers (1)

mehdy
mehdy

Reputation: 3374

I suggest you remove all of the *.py files from migrations except the __init__.py. Then have clean database and run ./manage.py makemigrations and ./manage.py migrate.

Just be sure __init__.py file exists inside the migrations package.

If it still didn't work, please add the output of those two commands to your question.

Upvotes: 1

Related Questions