我在尝试解决User Registration with error: no such table: auth_user
后收到错误
通过关注Manager isn't available; User has been swapped for 'pet.Person'
我仍然无法使用我的自定义用户注册表注册用户,而且我已经被困了将近2周。我很抱歉,如果我问一个非常基本的问题,但我只是想不通为什么我仍然无法注册我的用户。我的注册页面不会验证。
profiles / views.py:
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
from custom_user.forms import CustomUserCreationForm
from django.contrib import auth
from django.contrib.auth import get_user_model
from django.http import HttpResponseRedirect
#Create your views here
def home(request):
return render(request, "home.html")
def login(request):
c = {}
c.update(csrf(request))
return render(request, "login.html", c)
def about(request):
context = locals()
template = 'about.html'
return render(request,template,context)
@login_required
def userProfile(request):
user = request.user
context = {'user': user}
template = 'profile.html'
return render(request,template,context)
def auth_view(request):
username = request.POST.get['username', '']
password = request.POST.get['password', '']
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return HTTpResponseRedirect('account/login')
else:
return HTTpResponseRedirect('account/login')
def register_success(request):
return render(request, 'accounts/register_success.html')
def logout(request):
auth.logout(request)
return render(request, 'logout.html')
CustomUser = get_user_model()
register / views.py:
from django.shortcuts import render, redirect
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect
from custom_user.forms import CustomUserCreationForm
#Create your views here
def register(request):
form = UserCreationForm(request.POST or None)
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect ('home.html')
else:
return render(request, 'accounts/register.html', {'form': form})
else:
return render(request, 'accounts/register.html', {'form': form})
def register_success(request):
return render(request, 'accounts/register_success.html')
CustomUser = get_user_model()
models.py:
from time import timezone
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.core.mail import send_mail
from django.utils.translation import ugettext_lazy as _
from datetime import datetime
now = datetime.now()
class CustomUserManager(BaseUserManager):
def _create_user(self, email, password, is_staff, is_superuser, **extra_fields):
"""
Creates and saves a User with the given email and password.
"""
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(email=email,
is_staff=is_staff, is_active=True,
is_superuser=is_superuser, last_login=now,
**extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
return self._create_user(email, password, False, False, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
return self._create_user(email, password, True, True, **extra_fields)
class CustomUser(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=254, unique=True)
first_name = models.CharField(max_length=254, blank=True)
second_name = models.CharField(max_length=254, blank=True)
email = models.EmailField(blank=True, unique=True)
address1 = models.CharField(max_length=254, blank=True)
address2 = models.CharField(max_length=254, blank=True)
area_code = models.CharField(max_length=20, blank=True)
country_code = models.CharField(max_length=10, blank=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'address1', 'address2', 'area_code', 'country_code']
objects = CustomUserManager()
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def get_full_name(self):
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
"Returns the short name for the user."
return self.first_name
def email_user(self, subject, message, from_email=None, **kwargs):
"""
Sends an email to this User.
"""
send_mail(subject, message, from_email, [self.email], **kwargs)
forms.py:
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
class CustomUserChangeForm(UserChangeForm):
def __init__(self, *args, **kargs):
super(CustomUserChangeForm, self).__init__(*args, **kargs)
del self.fields['username']
class Meta:
CustomUser = get_user_model()
class CustomUserCreationForm(UserCreationForm):
def __init__(self, *args, **kargs):
super(CustomUserCreationForm, self).__init__( *args, **kargs)
del self.fields['username']
class Meta:
CustomUser = get_user_model()
def clean_username(self):
username = self.cleaned_data["username"]
try:
get_user_model().objects.get(username=username)
except get_user_model().DoesNotExist:
return username
raise forms.ValidationError(self.error_message['duplicate_username'])
admin.py:
from django.contrib.auth import get_user_model
from django.contrib import admin
from custom_user.models import CustomUser
# Register your models here.
from .models import profile
class profileAdmin(admin.ModelAdmin):
class Meta:
CustomUser = get_user_model()
admin.site.register(CustomUser)
追溯:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/accounts/register/
Django Version: 1.11.6
Python Version: 3.5.4
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'profiles',
'contact',
'crispy_forms',
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'checkout',
'custom_user']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\core\handlers\exception.py" in inner
41. response = get_response(request)
File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Adila\Documents\tryFOUR\src\register\views.py" in register
12. if form.is_valid():
File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\forms\forms.py" in is_valid
183. return self.is_bound and not self.errors
File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\forms\forms.py" in errors
175. self.full_clean()
File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\forms\forms.py" in full_clean
386. self._post_clean()
File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\forms\models.py" in _post_clean
413. self.instance.full_clean(exclude=exclude, validate_unique=False)
File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\db\models\base.py" in full_clean
1235. self.clean()
File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\contrib\auth\models.py" in clean
349. self.email = self.__class__.objects.normalize_email(self.email)
File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\db\models\manager.py" in __get__
198. cls._meta.swapped,
Exception Type: AttributeError at /accounts/register/
Exception Value: Manager isn't available; 'auth.User' has been swapped for 'custom_user.CustomUser'
答案 0 :(得分:0)
在views.py中删除
from django.contrib.auth.forms import UserCreationForm
并在下面使用CustomUserCreationForm代替UserCreationForm。