Django-oauth2-provider with custom user model?
I am really stuck with my project right now. I am trying to implement Oauth2 for my application. I learned a lot about django-oauth2-provider and tried it. The only problem is that it uses the User model in django.contrib.auth. The primary users of our site are saved in a custom User model, which does not inherit or extend the model to django.contrib.auth.
Can I use my custom model to create clients and token?
If django-oauth2-provider cannot be used for this purpose, can anyone recommend me some oauth2 library with the ability to implement oauth2 with my own model.
Respectfully,
Sushant Karki
source to share
As in the previous answer, you have to expand AbstractUser
from django.contrib.auth.models
.
The issue with the access token that the OP is accessing occurs when the parameter is changed AUTH_USER_MODEL
AFTER django-oauth2-provider
.
When migrated, django-oauth2-provider
it creates a key constraint between the user model and django-oauth2-provider.
The solution is very simple:
- Create a new user model and change the setting
AUTH_USER_MODEL
. - Go to a table
django_migration
in your database. - Delete all lines
django-oauth2-provider
. - run
python manage.py makemigrations
- run
python manage.py migrate
The tables are now django-oauth2-provider
connected to the RIGHT User model.
source to share
django-oauth2-provider retrieves the user model using settings.AUTH_USER_MODEL
, with a fallback toauth.User
. If you extend AbstractUser
, your user model will include all fields auth.User
plus any additional fields you specify.
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
some_additional_field = models.BooleanField(default=False)
Specify the user model to be used as follows settings.py
::
AUTH_USER_MODEL = 'user_api.User'
If you don't want your user to be on AbstractUser
, you will also need to write your own custom manager, for example. by expandingBaseUserManager
You can read more about how to set up a custom django model here .
source to share