skip to Main Content

After login I want to access User details when ever I want (Particularly in navigation bar).
I did not use user model provided in django. I created my own model like this for authentication.
My database is stored in mysql on phpmyadmin(Xampp).

AdminUser Model

class adminUser(models.Model):
    username=models.CharField(max_length=50)
    firstname=models.CharField(max_length=50)
    department=models.CharField(max_length=50)
    name=models.CharField(max_length=50)
    mail=models.CharField(max_length=50)
    id=models.IntegerField(primary_key=True)
    password=models.CharField(max_length=200)
    

    class Meta:
        db_table="admin_users"


admin_users.py


def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        if username is not None and password is not None:
            user=adminUser.objects.get(username=username)
            hashed_password = user.password
            is_check = bcrypt.checkpw(password.encode('utf8'),hashed_password.encode('utf8'))
            print(is_check)
            if is_check==True:
                return redirect(reverse('faq_index'))
            else:
                return render(request,'AdminUsers/login.html')
    return render(request,'AdminUsers/login.html')

During the login User Details can be only access by login function but I want to access user details in all pages for navigation bar and also want to find out whether user is authenticated or not. As I am not using User Model defined in django so I can not use user.is_authenticated(). So How do I do this?

2

Answers


  1. First, inherit your user model from AbstractBaseUser. It gives you some features like is_authenticated, set_password and etc

    Then define your custom user model as AUTH_USER_MODEL in your settings.py

    After these, django treats to your custom user as its default user

    models.py

    from django.contrib.auth.base_user import AbstractBaseUser
    
    
    class CustomUser(AbstractBaseUser):
        ...
    

    settings.py

    AUTH_USER_MODEL = 'myapp.MyUser'
    

    Docs in https://docs.djangoproject.com/en/3.2/topics/auth/customizing/

    Login or Signup to reply.
  2. I’m gonna recommend you take a step back, and extend the built-in User model instead of creating your own.

    As mentioned by @Amin, you can extend the AbstractBaseUser class to create a custom User model, and override the AUTH_USER_MODEL in settings.py.

    However, you can easily add a Profile model that has a one-to-one relationship with the built-in User model that does not require any overrides (which method is better escapes me at the moment, but I use the following method without issue):

    from django.conf import settings
    from django.contrib.auth import get_user_model
    from django.db import models
                                                                                                                                                                                     
    UserModel = get_user_model()
    
    
    class Profile(models.Model):
        user = models.OneToOneField(UserModel, on_delete=models.CASCADE)
        # add your desired fields here
        department=models.CharField(max_length=50)
    

    Then, in the same folder as contains your models.py, create a file called signals.py, and add the following code:

    from django.conf import settings
    from django.db.models.signals import post_save
    from django.dispatch import receiver
    
    from .models import Profile
    
    
    @receiver(post_save, sender=settings.AUTH_USER_MODEL)
    def create_user_settings(sender, instance, created, **kwargs):
        if created:
            Profile.objects.create(user=instance)
    

    This will trigger the creation of a new Profile object whenever a User object is created.

    Then, add the following to the same folder’s apps.py (Assuming the app’s name is users… make it match the name of the app that contains your Profile model):

    from django.apps import AppConfig
    
    
    class UsersConfig(AppConfig):
        default_auto_field = 'django.db.models.BigAutoField'
        name = 'users'
    
        def ready(self):
            import users.signals
    

    Now, after you run your migrations, you will be able to use the built-in User model, and add additional fields to it as desired in the Profile model.

    The only downside is that it will require a little extra work if you want to modify the User model and the Profile model on the same page (ie. you won’t just be able to specify the model name in an UpdateView).

    I don’t remember where I found this method. I believe it was adapted from this page on simpleisbetterthancomplex.com, but I’m not 100% sure.

    At any rate, Django automatically creates a primary key id for you, so you probably don’t need to manually define that in your model.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search