C
C
carrallton2020-10-15 13:14:53
Django
carrallton, 2020-10-15 13:14:53

How to access fields in BaseAbstractUser?

Hello, I am doing user registration with AbstractBaseUser
views.py

from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate
from account.forms import RegistrationForm
from store.models import Customer
from .models import Account
from .decorators import *


def registration_view(request):
  context = {}
  if request.POST:
    form = RegistrationForm(request.POST)
    if form.is_valid():
      form.save()
      email = form.cleaned_data.get('email')
      raw_password = form.cleaned_data.get('password1')
      account = authenticate(email=email, password=raw_password)
      Customer.objects.create(user=account, email=account.email)
      login(request, account)
      return redirect('store')
    else:
      context['registration_form'] = form
  else: 
    form = RegistrationForm()
    context['registration_form'] = form
  return render(request, 'account/register.html', context)


Issue:
Customer.objects.create(user=account, email=account.email) throws an IntegrityError at /register/
UNIQUE constraint failed: store_customer.user_id.

How to correctly access the fields of the account model or is the problem something else?

user model
class Account(AbstractBaseUser):
  email= models.EmailField(verbose_name="email", max_length=60, unique=True)
  username = models.CharField(max_length=30, unique=True)
  date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
  last_login = models.DateTimeField(verbose_name='last login', auto_now=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)


customer model:
class Customer(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True)
    name = models.CharField(max_length=200, null=True)
    email = models.CharField(max_length=200, null=True)
    phone_number = PhoneNumberField(null=True, blank=True)
    date_created = models.DateTimeField(auto_now_add=True, null=True)

    class Meta:
        verbose_name_plural = "Customers"

    def __str__(self):
        return str(self.name)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question