0

I am creating my custom user model for my web application This is the code I wrote for model in model.py

model.py

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager


# Create your models here.

# Custom User Manager
class UserManager(BaseUserManager):
    def create_user(self, username, email, password=None):
        if not email:
            raise ValueError("Valid Email Address required.")

        if not username:
            raise ValueError("Valid username is Required.")

        user = self.model(
            email = self.normalize_email(email),
            username = self.get_by_natural_key(username)
        )

        user.set_password(password)
        user.save(using = self._db)
        return user

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



# Custom User Model
class User(AbstractBaseUser):
    _id = models.AutoField
    email = models.EmailField(verbose_name='email', max_length=255, unique=True)
    username = models.CharField(verbose_name='username', max_length = 100, unique=True)
    name = models.CharField(max_length = 100)
    date_joined = models.DateTimeField(verbose_name="date-joined", auto_now_add=True)
    last_login = models.DateTimeField(verbose_name="last-login", auto_now=True)
    category = models.CharField(max_length=50, default= "teacher")
    is_admin = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    objects = UserManager()
    def __str__(self):
        return self.email
        return self.username

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

    def has_module_perms(self, app_label):
        return True

I am also modifying the admin page to show some fields. admin.py

class UserAdmin(BaseUserAdmin):

    # 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','username', 'last_login', 'is_admin')
    list_filter = ('is_admin',)
    readonly_fields = ()
    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('Personal info', {'fields': ('last_login',)}),
        ('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', 'last_login', 'password1', 'password2'),
        }),
    )
    search_fields = ('email',)
    ordering = ('email',)
    filter_horizontal = ()

admin.site.register(User, UserAdmin)
    

views.py

from django.shortcuts import render, redirect
from django.shortcuts import get_object_or_404
from django.http import HttpResponse
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.decorators import permission_required, login_required
from django.contrib import messages
from teacher.models import User, wreport, dreport
from chili_pili.views import home

# Create your views here.
# There are multiple functions in My view.py so I am only putting few functions as example.

def loginview(request):
    if request.method == "POST":
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username = username, password = password)
        print (user)
        if user is not None:
            login(request, user)
            print (user)
            messages.success(request, "You have successfully Logged In.")
            return redirect('index')
        else:
            messages.error(request, "You have entered invalid credentials. Please try again")
            return redirect('login')
    else:
        return render(request, 'teacher/login.html')

def index(request):
    return render(request, 'teacher/report.html')

def home1(request):
    home()  
    
@login_required(login_url='login')
def admin(request):
    if request.user.is_superuser:
        return render(request, 'teacher/admin.html')

    else:
        messages.info(request, "You don't have permission to view admin page. Please Contact Site-Administrator for access.")
        return render(request, 'teacher/report.html')

@login_required(login_url='login')
def weekly(request):
    if request.method == 'POST':
        tname1 = request.POST['tname']
        sname1 = request.POST['sname']
        date1 = request.POST['date']
        objective1 = request.POST['objective']
        tplan1 = request.POST['tplan']
        how1 = request.POST['how']
        material1 = request.POST['material']
        extra1 = request.POST['extra']

        report = wreport(tname = tname1, sname = sname1, fdate = date1, objective = objective1, tplan = tplan1, how = how1, material = material1, extra = extra1)
        report.save()

        messages.success(request, "Your report was submitted Successfully.")
    return render(request, 'teacher/weekly.html')
def logout_request(request):
    logout(request)
    messages.info(request, "You have Successfully Logged Out.")
    return redirect('login')

I am trying to create a superuser via commandline and After entering all details for superuser I am getting

Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "/home/sahilm/Documents/Programming_Projects/Python/Chili-pili/chili_pili/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "/home/sahilm/Documents/Programming_Projects/Python/Chili-pili/chili_pili/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/sahilm/Documents/Programming_Projects/Python/Chili-pili/chili_pili/env/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/sahilm/Documents/Programming_Projects/Python/Chili-pili/chili_pili/env/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 79, in execute
    return super().execute(*args, **options)
  File "/home/sahilm/Documents/Programming_Projects/Python/Chili-pili/chili_pili/env/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute
    output = self.handle(*args, **options)
  File "/home/sahilm/Documents/Programming_Projects/Python/Chili-pili/chili_pili/env/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 189, in handle
    self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
  File "/home/sahilm/Documents/Programming_Projects/Python/Chili-pili/chili_pili/teacher/models.py", line 33, in create_superuser
    username= self.get_by_natural_key(username),
  File "/home/sahilm/Documents/Programming_Projects/Python/Chili-pili/chili_pili/env/lib/python3.8/site-packages/django/contrib/auth/base_user.py", line 45, in get_by_natural_key
    return self.get(**{self.model.USERNAME_FIELD: username})
  File "/home/sahilm/Documents/Programming_Projects/Python/Chili-pili/chili_pili/env/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/sahilm/Documents/Programming_Projects/Python/Chili-pili/chili_pili/env/lib/python3.8/site-packages/django/db/models/query.py", line 429, in get
    raise self.model.DoesNotExist(
teacher.models.DoesNotExist: User matching query does not exist. 

I have tried to set username differently but it didn't help. I also tried deleting initial migrations and database assuming user may be present but it still gives me this error.

3
  • @thebjorn Thanks for pointing out my mistakes. Now fixed. Hope you can help me get a solution Commented Aug 12, 2020 at 7:21
  • 1
    Where does app.models.DoesNotExist: User matching query does not exist. come from (a traceback would be really helpful). Commented Aug 12, 2020 at 8:05
  • I am not able to understand traceback error so I have updated the post with Traceback Error Commented Aug 12, 2020 at 8:11

1 Answer 1

1

Your problem lies in the middle of your User_manager codes.

user = self.model(
    email = self.normalize_email(email),
    username = self.get_by_natural_key(username)
)

username = self.get_by_natural_key(username) will execute a query based on username which is not created before so it will raise a DoesNotExist error type. I think change this part to something like:

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

will solve your problem.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.