简体   繁体   中英

Django saving the registration extends AbstractBaseUser

Good day SO.

I am new to Django and having troubles with something basic. What I am trying to do is when I click on register, I want to create an Account and at the same time, a company account. When I click on sumbit, the template returns my Account(the OneToOneField) This field is required .

Though my methods might be not aligned with good practice, but I hope that you can help me with this. I have been trying to check with other resources for two days but I can't seem to find the solution to my concern.

Here is my forms.py:

from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import Account, CompanyAccount

class AccountCreationForm(UserCreationForm):
    email           = forms.EmailField(max_length=60, help_text="Required")
    class Meta:
        model = Account
        fields = ("email", "username", "password1", "password2", "account_type")

class CompanyAccountForm(forms.ModelForm):
    class Meta:
        model = CompanyAccount
        fields = "__all__"

my models.py:

    from django.db import models
    from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
    
    # Create your models here.
    
    class MyAccountManager(BaseUserManager):
        def create_user(self, email, username, account_type, password):
            if not email:
                raise ValueError("Users must have an Email Address")
            if not username:
                raise ValueError("Users must have an Username")
            if not account_type:
                raise ValueError("Users must have an Account Type")
    
            user = self.model(
                email=self.normalize_email(email),
                username=username,
                password=password,
                account_type=account_type,
            )
    
            user.set_password(password)
            user.save(using=self._db)
            return user
    
        def create_superuser(self, email, username, account_type, password):
            user = self.create_user(
                email=self.normalize_email(email),
                username=username,
                password=password,
                account_type=account_type,
            )
            user.is_admin = True
            user.is_staff = True
            user.is_superuser = True
            user.save(using=self._db)
            return user
    
    class Account(AbstractBaseUser):
        email           = models.EmailField(verbose_name='Email', max_length=60, default='', null=False, unique=True)
        username        = models.CharField(verbose_name='Username', max_length=50, default='', null=False, unique=True)
        date_joined     = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
        last_joined     = models.DateTimeField(verbose_name='last joined', auto_now_add=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)
    
        ACCOUNT_TYPE_CHOICES = (
            (1, 'Applicant'),
            (2, 'Company'),
            (3, 'Client'),
        )
    
        account_type    = models.PositiveSmallIntegerField(default=0, choices=ACCOUNT_TYPE_CHOICES)
    
        USERNAME_FIELD = 'email'
        REQUIRED_FIELDS = ['username', 'account_type', ]
    
        objects = MyAccountManager()
    
        def __str__(self):
            return self.username
    
        def has_perm(self, perm, obj=None):
            return self.is_admin
    
        def has_module_perms(self, app_label):
            return True
    
    class CompanyAccount(models.Model):
    
        account = models.OneToOneField(Account, on_delete=models.CASCADE)
        created = models.DateTimeField(auto_now_add=True)
        company_name = models.CharField(max_length=100, default='', null=False)

views.py

context = {}
if request.method == "POST":
    rForm = AccountCreationForm(request.POST)
    cForm = CompanyAccountForm(request.POST)
    if rForm.is_valid() and cForm.is_valid():
        rForm.save()
        cForm.save()

else:
    rForm = AccountCreationForm()
    context['rForm'] = rForm
    cForm = CompanyAccountForm()
    context['cForm'] = cForm

return render(request, 'registration/company_registration_form.html', context)

If you want your model's field to be allowed to be empty when submitting forms, add blank=True :

account = models.OneToOneField(Account, on_delete=models.CASCADE, blank=True)

https://docs.djangoproject.com/en/3.1/ref/models/fields/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM