Search code examples
djangosessiondjango-modelsdjango-rest-frameworkdjango-sessions

How do I use Sessions with Custom User Model using Django REST Framework?


I am currently working on a project which involves using Django solely for Back-end API endpoints using class-based views to authenticate and serve database content to users on the Front-end.

class UserLogin(APIView): # User Login
def post(self, request, format=None):
    print(request)
    try:
        User_Cred.objects.get(username=request.data['username'], password=request.data['password']) # Retrieves user record
        pass # TEMPORARY

    except User_Cred.DoesNotExist: # If User Record does not exist,
        raise Http404

Right now, I'm trying to figure out how to implement sessions for user authentication. I know that Django has some sort of integration with sessions. However, I am not using Django's default user model but a custom one instead (see below).

class Users(models.Model):
username = models.CharField(max_length=100, unique=True)
password = models.CharField(max_length=100)
def __str__(self):
    return self.username

Is there any way I can use my custom user model for session authentication? Thanks in advance.


Solution

  • To use a custom User model you simply have to add this line to your settings.py

    AUTH_USER_MODEL = "your_app_name.Users"
    

    Then for your permissions and authentication system, you can follow this doc to set it up:

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