我正在一个项目中使用Django的AbstractUser类。我已经创建了超级用户。每当我通过界面或admin创建新用户时,所有现有用户(包括超级用户)都会被删除。我在代码中找不到任何错误。
from django.db import models
from django.conf import settings
from django.contrib.auth.models import AbstractUser
from datetime import date
class CustomUser(AbstractUser):
employee_id = models.IntegerField(primary_key=True,default=0)
dateofbirth = models.DateField(default=date.today)
contact = models.CharField(max_length=10,default="No contact")
address = models.CharField(max_length=300,default="No address given")
image = models.ImageField(default=None)
manager_id = models.IntegerField(default=0)
date_of_joining = models.DateField(default=date.today)
date_of_termination = models.DateField(default=date.today)
status = models.CharField(max_length=8,default="inactive")
role_id = models.IntegerField(default=0)
def __str__(self):
return self.username
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from .forms import CustomUserCreationForm
from django.shortcuts import render, redirect
def signup(request):
if request.method == 'POST':
form = CustomUserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('emp_dashboard')
else:
form = CustomUserCreationForm()
return render(request, 'signup.html', {'form': form})
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = CustomUser
fields = ('username', 'email')
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = CustomUser
fields = ('username', 'email')
INSTALLED_APPS = [
'portal', #App Name
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
AUTH_USER_MODEL = 'portal.CustomUser'
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from django.contrib.admin.sites import AlreadyRegistered
from django.apps import apps
from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import CustomUser
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = CustomUser
list_display = ['username','email','is_superuser']
fieldsets = (
(('User'), {'fields': ('username', 'email','is_active','is_superuser','is_staff','employee_id','dateofbirth','contact','address','image','manager_id','date_of_joining','date_of_termination','status','role_id')}),
)
admin.site.register(CustomUser, CustomUserAdmin)
for model in apps.get_app_config('portal').models.values():
try:
admin.site.register(model)
except AlreadyRegistered:
pass