0

I am creating an authentication system using django 1.10.5. I am using email as the unique identifier instead of username. I followed these instructions

HOW to use email

I created my Customer User Model and Custom User Manager for the new User Model

from django.contrib.auth.models import AbstractUser, BaseUserManager 
from django.db import models 
from django.utils.translation import ugettext_lazy as _


class UserManager(BaseUserManager):


    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):

        if not email:

            raise ValueError('THE email is not set')

        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password=None, **extra_fields):

        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(email, password, **extra_fields)


    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')

        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(email, password, **extra_fields)



class User(AbstractUser):


    username = None 
    email = models.EmailField(_('email address'), unique = True )


    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = UserManager()

I added the Custom User Model in my settings document :

AUTH_USER_MODEL = 'Identities.User'

I then registered my new User Model in the administration document

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin
from django.utils.translation import ugettext_lazy as _


# Register your models here.

from .models import User



@admin.register(User)

class UserAdmin(DjangoUserAdmin):

    # Define admin model for custom User model with no email field 

    fieldsets = (

        (None, {'fields': ('email', 'password')}),
        (_('Personal info'), {'fields': ('first_name', 'last_name')}),
        (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups',
                                       'user_permissions')}),
        (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
    )

    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'password1', 'password2'),
            })

    )

    list_display = ('email', 'first_name', 'last_name', 'is_staff')
    search_fields = ('email', 'first_name', 'last_name')
    ordering = ('email',)

I created my new model using migrate and makemigrations, however when I tried to create a new account with this new user model I keep getting this error

OperationalError at /Self/register/ no such table: auth_user Request Method: POST Request URL: http://127.0.0.1:8000/Self/register/ Django Version: 1.10.5 Exception Type: OperationalError Exception Value: no such table: auth_user

The message also contains this:

The above exception (no such table: auth_user) was the direct cause of the following exception:

It directs me to this application file :

/Users/iivri.andre/Identity platform/app/Self/Identities/views.py in register

form.save()

This is the code for the register view :

def register(request):

    if request.method == 'POST':

        form = CreateAccountForm(request.POST)

        if form.is_valid():
            form.save()
            return redirect('/Self')
        else:
            return redirect(reverse('Identities:iivri'))

    else:

        form = CreateAccountForm()
        args = {'form':form}
        return render(request, 'Identities/create_account.html', args)

Update

This is the code in my forms document:

from django import forms 
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, UserChangeForm


# Create custom user registration

class CreateAccountForm(UserCreationForm):

    email = forms.EmailField(required=True)


    class Meta:

        model = User 

        fields = (

        'first_name',
        'last_name',
        'email',
        'password1',
        'password2'

        )

        def save(self, commit = True):
            user = super(CreateAccountForm, self).save(commit = False)
            user.first_name = self.cleaned_data['first_name']
            user.last_name = self.cleaned_data['last_name']
            user.email = self.cleaned_data['email']

            if commit: 
                user.save()

            return user 


class UpdateAccountForm(UserChangeForm):

    # exclude certain elements of the form using *fields and *exclude 

    class Meta : 
        # specifiy model being used 
        model = User

        # list fields to include
        fields = (

            'email',
            'first_name',
            'last_name',
            'password'
        )

I have already tried This, This, and This and I am still getting the error.

How do I fix this.

Waltham WECAN
  • 481
  • 4
  • 11
  • 26

1 Answers1

2

Although you have created custom user model but you are still trying to use Django default user model from django.contrib.auth.models import User, you shouldn't do that instead use get_user_model which will return the correct user model:

from django.contrib.auth import get_user_model

class CreateAccountForm(UserCreationForm):
    email = forms.EmailField(required=True)

    class Meta:
        model=get_user_model()

Use model=get_user_model() for other forms as well.

Aamir Rind
  • 38,793
  • 23
  • 126
  • 164