Created
April 18, 2013 16:22
-
-
Save percyperez/5414079 to your computer and use it in GitHub Desktop.
Custom User Model with Django 1.5 due to "relation auth_user doesn't exist..." error using AbstractUser class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# forms.py | |
from django import forms | |
from django.contrib.auth.forms import UserChangeForm, UserCreationForm | |
from .models import User # Your custom user model | |
class CustomUserCreationForm(UserCreationForm): | |
class Meta: | |
model = User | |
def clean_username(self): | |
# Taken from https://github.com/django/django/blob/master/django/contrib/auth/forms.py#L92 | |
# Since User.username is unique, this check is redundant, | |
# but it sets a nicer error message than the ORM. See #13147. | |
username = self.cleaned_data["username"] | |
try: | |
self._meta.model._default_manager.get(username=username) # Use the custom user model | |
except self._meta.model.DoesNotExist: | |
return username | |
raise forms.ValidationError(self.error_messages['duplicate_username']) | |
class CustomUserChangeForm(UserChangeForm): | |
class Meta: | |
model = User | |
# admin.py | |
from django.contrib import admin | |
from django.contrib.auth.admin import UserAdmin | |
from .forms import CustomUserChangeForm, CustomUserCreationForm | |
from .models import User | |
class CustomUserAdmin(UserAdmin): | |
model = User | |
form = CustomUserChangeForm | |
add_form = CustomUserCreationForm | |
save_on_top = True | |
admin.site.register(User, CustomUserAdmin) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks a lot, It works for me on Django==1.8.5 :)