I am a newbie at Django and I have come across this problem with my code.
I have a Custom User Model and an Account model which are related by many-to-many field.
During SignUp a user is asked to either create an Account or not ( join other account through a link ).
If the User creates an Account then he is the owner of the account and other Users can join the account.(Did not finish the code for ownership)
One User can be a part of several accounts at the same time.
Creation of Account(or not) and the User takes place in the Signup view.
I read up about the nested serializer in the documentation and i think this should create the two models instances.
How to create relationships in one view using nested serializers?
Other Approaches to solve the issue?
Models
class Account(models.Model):
AccountName = models.TextField(max_length=100, blank=False, null=False)
class User(AbstractBaseUser):
AccountName = models.ManyToManyField(Account)
CreateAccount = models.BooleanField(blank=False, null=False)
EmailId = models.EmailField(max_length=128, blank=False, null=False, unique=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
USERNAME_FIELD = 'EmailId'
REQUIRED_FIELDS = ['AccountName', 'CreateAccount',]
# Implemented the other req. functions
objects = MyAccountManager()
Serializers
class AccountCreationSerializer(ModelSerializer):
class Meta:
model = Account
fields = ['AccountName']
class SignUpSerializer(ModelSerializer):
AccountName = AccountCreationSerializer()
class Meta:
model = User
fields = ['EmailId', 'AccountName', 'CreateAccount', 'password']
extra_kwargs = {'password': {'write_only': True, 'required': True}}
def create(self, validated_data):
AccountName = validated_data.pop('AccountName')
if validated_data['CreateAccount']: #Create only when this is True
Account.objects.create(AccountName=AccountName, **AccountName)
userAcc = User.objects.create_user(**validated_data)
return userAcc
View
class SignUpView(APIView):
def post(request):
# to edit
signup_serializer = SignUpSerializer(data=request.data)
# rest of the view
The request
// Ignoring the quotes
EmailID: xyz#gmail.com
AccountName: TestAcc
CreateAccount: False
Password: ****
Error:
Direct assignment to the forward side of a many-to-many set is prohibited. Use AccountName.set() instead.
Create_user in Custom model
def create_user(self, EmailId, AccountName, CreateAccount, password):
if not EmailId:
raise ValueError("Users must have an email")
user = self.model(
EmailId=self.normalize_email(EmailId),
AccountName=AccountName,
CreateAccount=CreateAccount,
)
user.set_password(password)
user.save(using=self._db)
return user
I am pretty sure I am making some mistake regarding the manytomany field but haven't been able to figure out the solution. Any help would be of benefit to me. TIA!
You can not save value directly to many-to-many field. Database does not allow you to do so. It only allows you to add them for associating the relationship between the two tables ( i.e User, Account ). Replace your code segment for Serializer file with the following one.
class AccountCreationSerializer(ModelSerializer):
class Meta:
model = Account
fields = ['AccountName']
class SignUpSerializer(ModelSerializer):
AccountName = serializers.SerializerMethodField()
class Meta:
model = User
fields = ['EmailId', 'AccountName', 'CreateAccount', 'password']
extra_kwargs = {'password': {'write_only': True, 'required': True}}
def validate(self, attrs):
attrs = super(SignUpSerializer, self).validate(attrs=attrs)
attrs.update({"AccountName": self.initial_data.get("AccountName")})
return attrs
def create(self, validated_data):
AccountName = validated_data.pop('AccountName')
acc = Account.objects.create(AccountName=AccountName) if "CreateAccount" in validated_data and validated_data['CreateAccount'] else None
userAcc = User.objects.create_user(**validated_data)
if acc:
userAcc.AccountName.add(acc)
return userAcc
Finally, replace your SignUpView class in the following way:
class SignUpView(APIView):
serializer_class = SignUpSerializer
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data)
is_valid_serializer = serializer.is_valid(raise_exception=True)
if is_valid_serializer:
with transaction.atomic():
serializer.save()
# Rest of your code segments to finalize the response
UPDATE
There is a problem with your create_user method. You are here passing the many-to-many field reference (AccountName), which you shouldn't. As I mentioned earlier, you can not save directly many-to-many field. You just need to associate the relation between them. Omit that and it will work!!!
Follow this new definition for this method (create_user).
def create_user(self, EmailId, CreateAccount, password):
if not EmailId:
raise ValueError("Users must have an email")
user = self.model(EmailId=self.normalize_email(EmailId), CreateAccount=CreateAccount)
user.set_password(password)
user.save(using=self._db)
return user
Related
I have this problem for a month.
I'm using abstractbasemodel and basemanagerto to create a login and signup API using rest framework.
However, when I create a user password, it is saved as raw data since I use set_password() method and custom model manager confuses me...
This is my code :
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ('id' ,'email' ,'name' ,'password')
extra_kwargs = {
'password':{
'write_only':'True',
'style': {'input_type': 'password'}
}
}
def create(self, validated_data):
user = UserProfile.people.create_user(
email = validated_data['email'],
name = validated_data['name'],
password = validated_data['password']
)
class UserProfileViewSet(viewsets.ModelViewSet):
serializer_class = serializers.UserProfileSerializer
queryset = models.UserProfile.people.all()
authentication_classes = (TokenAuthentication, )
permission_classes = (UpdateOwnProfile, )
filter_backends = (SearchFilter, )
search_fields = ('name', 'email')
class UserLoginApiView(ObtainAuthToken):
renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
class UserProfileManager(BaseUserManager):
def create_user(self, email, name, password=None):
print("user model manager")
if not email:
raise ValueError('User Must Have an Email Address')
email = self.normalize_email(email)
user = self.model(email=email, name=name )
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, name, password):
user = self.create_user(email, name, password)
user.is_superuser = True
user.is_staff = True
user.save(using=self._db)
return user
class UserProfile(AbstractBaseUser,PermissionsMixin):
email = models.EmailField(max_length=255,unique=True)
name = models.CharField(max_length=255)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
people = UserProfileManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name']
def get_full_name(self):
return self.name
def get_short_name(self):
return self.name
def __str__(self):
return self.email
class Profile(models.Model):
user = models.OneToOneField(UserProfile,on_delete=models.CASCADE,relat ed_name="Profile")
location = models.CharField(max_length=100,blank=True,null=True)
bio = models.CharField(max_length=100,blank=True,null=True)
creationDate = models.DateTimeField(auto_now_add=True)
follower = models.ManyToManyField(UserProfile,related_name="Following",blank=True)
class Meta:
verbose_name='Profile'
verbose_name_plural='Profiles'
I also defined auth user model in settings :
AUTH_USER_MODEL='profiles.UserProfile'
to make sure Django uses my custom user model.
I don't know whats wrong as there is no error and only superusers that are created in terminal using manage.py are saved with hashed password.
Users which are created with my viewsets are saved with raw password.
First, I named the model manager "objects" and now, its people but the create user method wont run at all.
You can use django's built in hasher to create hashed password. It can be applied in .create method. First import from django.contrib.auth.hashers import make_password and then modify .create() method,
def create(self, validated_data):
user = UserProfile.people.create_user(
email = validated_data['email'],
name = validated_data['name'],
password = make_password(validated_data['password']) # here
)
return user
Or
if you don't override the .create() method then add the following validate_password method in serializer,
The validate_password is ran, everytime a new object has to be created
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ('id' ,'email' ,'name' ,'password')
extra_kwargs = {
'password':{
'write_only':'True',
'style': {'input_type': 'password'}
}
}
def validate_password(self, value: str) -> str:
return make_password(value)
I am trying to implement multiple user types in DRF and I'm doing that by having a
User Model - which has login related fields and common fields in all the roles and also a choice field denoting type of user.
Customer Model - OneToOneField with user model.
Seller Model - OneToOneField with user model.
I have set up authentication and permissions for User model and now I'm able to log in. I want the logged in user to be able to create his respective profile (based on user_type field of User model).
class User(AbstractBaseUser, PermissionsMixin):
""" A Generic User inside our system. The fields used are common to all users in system. """
....
class Customer(models.Model):
"""A Class to represent a Customer in System """
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
Now I am trying to figure out how to allow a user to create a profile respective to his user_type (customer/seller). and the more confusing part is how do I set the user to current logged in user for my CustomerSerializer or SellerSerializer
This is the permission class I'm trying to use:
class UpdateCustomerProfile(permissions.BasePermission):
"""Allow users to edit their own profile """
def has_object_permission(self, request, view, obj):
"""Check if user is trying to edit their own profile"""
return obj.user.id == request.user.id
and this is the customer serializer:
class CustomerSerializer(serializers.ModelSerializer):
"""A Serizlier class for customer """
class Meta:
model = models.Customer
fields = ('user', 'first_name', 'last_name', 'dob', 'gender')
def create(self, validated_data):
"""Create and return a new customer."""
CustomerViewSet:
class CustomerViewSet(viewsets.ModelViewSet):
"""Handle creating reading and updating Users in system"""
serializer_class = serializers.CustomerSerializer
queryset = models.User.objects.filter( user_type = "CS" )
authentication_classes = (TokenAuthentication,)
permission_classes = (permissions.UpdateCustomerProfile,)
But I get an error
AttributeError at /api/customer-profile/
Got AttributeError when attempting to get a value for field user on serializer CustomerSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the User instance.
Original exception text was: 'User' object has no attribute 'user'.
I'm new to Django so I'm not sure If this is a way to do it or if I'm doing anything wrong. How can I fix this? Any examples projects following similar strategy would also be very helpful.
Since your serializer is for a Customer, your queryset should be for a Customer:
queryset = models.Customer.objects.filter(user=request.user)
for example, if you only want to the Customer profile of the current user.
class CustomerViewSet(viewsets.ModelViewSet):
"""Handle creating reading and updating Users in system"""
serializer_class = serializers.CustomerSerializer
#you are using customer model for serializer but for query set you are using
#User model.
queryset = models.Customer.objects.filter( user__type = "CS" )
authentication_classes = (TokenAuthentication,)
permission_classes = (permissions.UpdateCustomerProfile,)
Hey got my code below to work for serializing registration with multiple user types. I followed this: https://www.freecodecamp.org/news/nested-relationships-in-serializers-for-onetoone-fields-in-django-rest-framework-bdb4720d81e6/
here is my models.py:
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
is_individual = models.BooleanField(default=False)
is_company = models.BooleanField(default=False)
class Company(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
company_name = models.CharField(max_length=100)
email_address = models.EmailField(max_length=254, blank=True, null=True)
class Individual(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
email_address = models.EmailField(max_length=254)
here is my serializers.py:
from rest_framework import serializers
from classroom.models import User, Individual, Company
from django.contrib.auth import authenticate
class IndividualSerializer(serializers.ModelSerializer):
class Meta:
model = Individual
fields = ('user', 'email_address')
class CompanySerializer(serializers.ModelSerializer):
class Meta:
model = Company
fields = ('user', 'email_address', 'company_name')
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'password', 'is_individual', 'is_company')
extra_kwargs = {'password': {'write_only': True}}
class IndividualRegisterSerializer(serializers.ModelSerializer):
user = UserSerializer(required=True)
class Meta:
model = Individual
fields = ('user', 'email_address')
extra_kwargs = {'password': {'write_only': True}, 'username': {'write_only': True}}
def create(self, validated_data, *args, **kwargs):
user = User.objects.create_user(validated_data['user']['username'], validated_data['email_address'], validated_data['user']['password'])
individual = Individual.objects.create(user=user, email_address=validated_data.pop('email_address'))
return individual
class CompanyRegisterSerializer(serializers.ModelSerializer):
user = UserSerializer(required=True)
class Meta:
model = Company
fields = ('user', 'company_name', 'email_address')
extra_kwargs = {'password': {'write_only': True}, 'username': {'write_only': True}}
def create(self, validated_data, *args, **kwargs):
user = User.objects.create_user(validated_data['user']['username'], validated_data['email_address'],
validated_data['user']['password'])
company = Company.objects.create(user=user, email_address=validated_data.pop('email_address'), company_name=validated_data.pop('company_name'))
return company
class IndividualLoginSerializer(serializers.Serializer):
username = serializers.CharField()
password = serializers.CharField()
def validate(self, data):
individual = authenticate(**data)
if individual and individual.is_active:
return individual
raise serializers.ValidationError("Incorrect Credentials")
class Meta:
fields = ['username','password','is_individual','is_company']
extra_kwargs = {'is_individual': {'required': False},
'is_company': {'required': False}}
and here is my api.py:
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import generics, permissions
from knox.models import AuthToken
from ..serializers import \
UserSerializer, \
IndividualRegisterSerializer, CompanyRegisterSerializer, \
class RegisterIndividualAPI(generics.GenericAPIView):
serializer_class = IndividualRegisterSerializer
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
individual = serializer.save()
individual_data = IndividualSerializer(individual, context=self.get_serializer_context()).data
return Response({
"individual": individual_data,
"username": individual.user.username,
"token": AuthToken.objects.create(individual.user)[1]
})
class RegisterCompanyAPI(generics.GenericAPIView):
serializer_class = CompanyRegisterSerializer
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
company = serializer.save()
company_data = CompanySerializer(company, context=self.get_serializer_context()).data
return Response({
"company": company_data,
"username": company.user.username,
"token": AuthToken.objects.create(company.user)[1]
})
class LoginCompanyAPI(generics.GenericAPIView):
serializer_class = CompanyLoginSerializer
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
company = serializer.validated_data
company_data = CompanySerializer(company, context=self.get_serializer_context()).data
return Response({
"company": company_data,
"username": company.user.username,
"token": AuthToken.objects.create(company.user)[1]
})
And here is my API POST request's body:
{
"user": {
"username":"nind5",
"password": "123456",
"is_individual" : "True",
"is_company" : "False"
},
"email_address":"n#gmail.com"
}
I also used this resource https://www.youtube.com/watch?v=0d7cIfiydAc&t=437s. Knox is explained in this video as well.
Also, use this online tool to view your db (db.sqlite3) tables : https://sqliteonline.com/
Best,
Nick
I am new to Django in general so please do not judge me harshly.
I have a custom User model and I use DRF for user profile creation. I normalize the email in the create_user (method of the BaseUserManager). I cannot find the way how to also normalize the value of an email field in the API Serializer. Basically, if I pass an email that already exists in the database, but just with capital letters in the domain, it will go through the Serializer's validation, however it will hit an Integrity Error after:
duplicate key value violates unique constraint "accounts_user_email_key"
DETAIL: Key (email)=(email#example.com) already exists.
Here is a shortened version of my UserManager method:
class UserManager(BaseUserManager):
def create_user(self, email, first_name, last_name, password):
#some validation logic
#...
user = self.model(
email=self.normalize_email(email),
first_name=first_name,
last_name=last_name
)
user.set_password(password)
user.save()
return user
#other stuff...
Here is a Serializer itself:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ('email', 'first_name', 'last_name', 'password')
extra_kwargs = {k: {'write_only': True} for k in fields}
#some password validation...
def create(self, validated_data):
user = models.User.objects.create_user(
email=validated_data['email'],
first_name=validated_data['first_name'],
last_name=validated_data['last_name'],
password=validated_data['password']
)
return user
Here is the view:
class UserCreate(generics.CreateAPIView):
serializer_class = serializers.UserSerializer
You can use field-level-validation in serializer:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ('email', 'first_name', 'last_name', 'password')
extra_kwargs = {k: {'write_only': True} for k in fields}
def validate_email(self, value):
norm_email = value.lower()
if models.User.objects.filter(email=norm_email).exists():
raise serializers.ValidationError("Not unique email")
return norm_email
I am currently using restful and serializers to create and update my user.
Somehow I am not able to update some of the fields if the field has to do with OneToOneField / ForeignKey.
in my models.py, my Student is actually connected to the django build in user model which includes the user's email and connected to the school model which has the name of the school
class Student(Model):
user = OneToOneField(settings.AUTH_USER_MODEL, on_delete=CASCADE)
date_of_birth = DateField(blank=True, null=True)
student_name = CharField(max_length=256)
school = ForeignKey(School,
on_delete=CASCADE,
related_name="%(class)ss",
related_query_name="%(class)s",
blank=True,
null=True)
in serializer.py I have
class StudentSerializer(ModelSerializer):
user_email = SerializerMethodField()
school_name = SerializerMethodField()
class Meta:
model = Student
fields = (
'user_email', 'student_name', 'phone', 'school_name')
def get_user_email(self, obj):
return obj.user.email
def get_school_name(self, obj):
return obj.school.school_name
def create(self, validated_data):
return Student.objects.create(**validated_data)
def update(self, instance, validated_data):
instance.user.email = validated_data.get('user_email', instance.user.email)
instance.student_name = validated_data.get('student_name', instance.student_name)
instance.phone = validated_data.get('phone', instance.phone)
instance.school.school_name = validated_data.get('school_name', instance.school.school_name)
instance.save()
return instance
in my view.py update function
class UserViewSet(ViewSet):
queryset = Student.objects.all()
def update(self, request, pk=None):
student = get_object_or_404(self.queryset, pk=pk)
serializer = StudentSerializer(student, data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return Response({'status': True})
return Response({'status': False, 'message': serializer.errors})
I am able to use the API view to pass in json and update the student_name and phone but as for the other two, user_email and school_name I am not able to update it. I don't get any error output when I submit the json though.
I realized the two fields that I am not able to update are because they OneToOneField / ForeignKey.
Can someone please give me a hand what I am missing here or what I can do to check?
Thanks in advance
I think your serializer isn't completed... the field of user and school is instance model, you need specific field in your serializer to implement the instance model, eg: with source='...' argument.
and example:
class VoteSerializer(serializers.ModelSerializer):
# by `username`
user = serializers.CharField(
source='user.username',
read_only=True
)
# by `pk/id`
candidate = serializers.IntegerField(
source='candidate.pk',
read_only=True
)
class Meta:
model = Vote
fields = ('user', 'candidate', 'score')
def create(self, validated_data):
return Vote.objects.create(**validated_data)
and in your case, perhaps is like this;
class StudentSerializer(ModelSerializer):
# by `pk/id` from the user
user = serializers.IntegerField(
source='user.pk',
read_only=True
)
school = serializers.IntegerField(
source='school.pk',
read_only=True
)
Since you are using SerializerMethodField which is readonly field (docs) for user_email and school_name so they won't be available in the validated_data.
Have you check the data you are receiving in validated_data
def update(self, instance, validated_data):
print('++'*22, validated_data)
return instance
The nested seriailzer / model / presentation actually helped me get the work done and pretty helpful.
An example is also provided here.
http://www.django-rest-framework.org/api-guide/serializers/#writing-update-methods-for-nested-representations
the above is continued from
http://www.django-rest-framework.org/api-guide/serializers/#writing-create-methods-for-nested-representations which contained how the nested serializer is being setup in the class and meta's fields
We're required to have two separate forms for two different types of users. Call them Client and Provider. Client would be the parent, base user, while Provider is a sort of extension. At any point a Client could become a Provider as well, while still maintaining status and information as a Client. So a Provider has both permissions as a Client and as a Provider.
I'm new to Django. All we're trying to do is register either user type, but have a one to one relation between Provider and Client tables if a user registers as a Provider straight away.
The issue we're having is in the adapter, we think. A provider registers fine, but ends up in the users_user table with no entry in the generated users_provider table. Is it the way we're trying to save and relate these two entities in the database, or something else?
We're trying to utilize allauth for authentication and registration.
Our code:
models.py:
class User(AbstractUser):
name = models.CharField(_('Name of User'), blank=True, max_length=255)
def __str__(self):
return self.username
def get_absolute_url(self):
return reverse('users:detail', kwargs={'username': self.username})
SEX = (
("M","MALE"),
("F","FEMALE"),
)
birthdate = models.DateField(_('Birth Date'), default=django.utils.timezone.now, blank=False)
sex = models.CharField(_('Sex'), choices=SEX, max_length=1, default="M")
isProvider = models.BooleanField(_('Provider'), default=False)
#Using User, not models.Model
class Provider(User):
HAS_BUSINESS = (
('YES','YES'),
('NO','NO'),
)
#Resolving asociation 1:1 to User
#NOTE: AUTH_USER_MODEL = users.User in setting
owner = models.OneToOneField(settings.AUTH_USER_MODEL)
has_business = models.CharField(_('Do you have your own business?'),max_length=2, choices=HAS_BUSINESS, default='NO')
isProvider = True
our forms.py
class ProviderForm(SignupForm,ModelForm):
name = forms.CharField(label='Name', strip=True, max_length=50)
lastname = forms.CharField(label='Last Name', strip=True, max_length=50)
Provider.isProvider = True
class Meta:
model = Provider
fields = '__all__'
exclude = GENERAL_EXCLUSIONS + [
'owner',
]
class ClientForm(SignupForm,ModelForm):
name = forms.CharField(label='Name', strip=True, max_length=50)
lastname = forms.CharField(label='Last Name', strip=True, max_length=50)
class Meta:
model = User
fields = "__all__"
exclude = GENERAL_EXCLUSIONS
def is_active(self):
return False
def __init__(self, *args, **kwargs):
super(ClientForm, self).__init__(*args, **kwargs)
views.py:
class ProviderRegisterView(SignupView):
template_name = 'account/form_provider.html'
form_class = ProviderForm
redirect_field_name = 'next'
view_name = 'registerprovider'
success_url = None
def get_context_data(self, **kwargs):
ret = super(ProviderRegisterView, self).get_context_data(**kwargs)
ret.update(self.kwargs)
return ret
registerprovider = ProviderRegisterView.as_view()
#View para el formulario de registro de usuarios clientes
class ClientRegisterView(SignupView):
template_name = 'account/form_client.html'
form_class = ClientForm
redirect_field_name = 'next'
view_name = 'registerclient'
success_url = None
def get_context_data(self, **kwargs):
ret = super(ClienteRegisterView, self).get_context_data(**kwargs)
ret.update(self.kwargs)
return ret
registerclient = ClienteRegisterView.as_view()
finally, our adapter.py:
#Per allauth documentation, settings changed:
#ACCOUNT_ADAPTER = 'projectname.users.adapters.RegisterUserAdapter'
class RegisterUserAdapter(DefaultAccountAdapter):
def save_user(self, request, user, form, commit=True):
data = form.cleaned_data
user.first_name = data['name']
user.last_name = data['lastname']
#Saving Client info
user.sex = data['sex']
user.birthdate = data['birthdate']
#Normal allauth saves
user.username = data['username']
user.email = data['email']
if user.isProvider:
p = Provider()
p.owner = user
p.has_business = data['has_business']
if 'password1' in data:
user.set_password(data['password1'])
else:
user.set_unusable_password()
self.populate_username(request, user)
if commit:
#Save user
user.save()
#If it's also a Provider, save the Provider
if user.isProvider:
p.save()
return user
Any help or tips would be greatly appreciated. If I left something out, please let me know. I'm not sure if the problem is in the model itself, the way we represent the form, or the adapter. The way it stands, it doesn't matter what form we use, it's always saved as the base User table (our Client) and the Provider table never gets information saved to it.
With Django's new custom user model, only one user model can be set as settings.AUTH_USER_MODEL. In your example, you can set this to your User model.
Then for the optional provider data, create a separate model that is referenced by OneToOneField from your User model.
class User(AbstractUser):
...
provider = models.OneToOneField(Provider, null=True)
class Provider(models.Model):
...
This is the easiest way to work with multiple user types in Django, given the AUTH_USER_MODEL constraint.
Also, it's best to only subclass abstract models, otherwise you get multitable inheritance which results in hidden implied JOINs, degrading performance.
Finally, you can create the Provider object in your custom form's form.is_valid() method and assign user.provider = provider.