AUTH_USER_MODEL
在 EDIT3 中解决了错误。密码仍然不会通过表单保存用户创建。
我正在使用 Django 1.5 玩新用户覆盖/扩展功能,我无法通过我的注册表单注册新用户 - 只能通过管理员。通过注册表单注册时,我收到以下错误:
Manager isn't available; User has been swapped for 'poker.PokerUser'
模型.py:
class PokerUser(AbstractUser):
poker_relate = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
token = models.EmailField()
USER_CHOICES = (
('1', 'Staker'),
('2', 'Horse')
)
user_type = models.CharField(choices=USER_CHOICES, max_length=10)
username1 = models.CharField(null=True, blank=True, max_length=40)
username2 = models.CharField(null=True, blank=True, max_length=40)
username3 = models.CharField(null=True, blank=True, max_length=40)
username4 = models.CharField(null=True, blank=True, max_length=40)
username5 = models.CharField(null=True, blank=True, max_length=40)
PokerUserForm
模型:
class PokerUserForm(UserCreationForm):
class Meta:
model = PokerUser
fields = ('username','password1','password2','email','user_type','token','username1','username2','username3','username4','username5',)
我试图更改模型中的PokerUserForm
模型以使用而不是通过设置而get_user_model()
不是显式定义模型,但随后我收到以下错误:model = get_user_model()
model = PokerUser
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'poker.PokerUser' that has not been installed
我AUTH_USER_MODEL
是settings.py
这样设置的:
AUTH_USER_MODEL = 'poker.PokerUser'
继续 - 我的注册视图位于views.py
:
def UserRegistration(request):
player = PokerUser()
if request.method == 'POST':
form = PokerUserForm(request.POST, instance=player)
if form.is_valid():
player.email_address = form.cleaned_data['email']
player.user_type = form.cleaned_data['user_type']
# if player is staker, token is their own email. otherwise their token is their staker's email and
# their relation is their staker
if player.user_type == '1' or player.user_type == 'staker':
player.token = player.email_address
else:
player.token = form.cleaned_data['token']
staker = PokerUser.objects.get(email=player.token)
player.poker_relate = staker
player.save()
return HttpResponseRedirect('/')
else:
form = PokerUserForm()
initialData = {'form': form}
csrfContext = RequestContext(request, initialData)
return render_to_response('registration/register.html', csrfContext)
编辑1:
根据文档,UserCreationForm
必须重新创建以与自定义用户类一起使用。
我覆盖了整个UserCreationForm
如下:
class UserCreationForm(forms.ModelForm):
"""
A form that creates a user, with no privileges, from the given username and
password.
"""
error_messages = {
'duplicate_username': _("A user with that username already exists."),
'password_mismatch': _("The two password fields didn't match."),
}
username = forms.RegexField(label=_("Username"), max_length=30,
regex=r'^[\w.@+-]+$',
help_text=_("Required. 30 characters or fewer. Letters, digits and "
"@/./+/-/_ only."),
error_messages={
'invalid': _("This value may contain only letters, numbers and "
"@/./+/-/_ characters.")})
password1 = forms.CharField(label=_("Password"),
widget=forms.PasswordInput)
password2 = forms.CharField(label=_("Password confirmation"),
widget=forms.PasswordInput,
help_text=_("Enter the same password as above, for verification."))
class Meta:
model = PokerUser
fields = ('username','password1','password2','email','user_type','token','username1','username2','username3','username4','username5',)
def clean_username(self):
# 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:
PokerUser.objects.get(username=username)
except PokerUser.DoesNotExist:
return username
raise forms.ValidationError(self.error_messages['duplicate_username'])
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'])
return password2
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
这能够解决此错误:
The Manager isn't available; User has been swapped for 'poker.PokerUser'
现在,用户已创建但无法登录。当我在管理员中检查用户时,所有信息似乎都是正确的,除了密码。在管理员中手动添加密码似乎无法正常工作。尽管如此,通过管理员添加用户仍然可以正常工作。
编辑2:
我仍然无法以通过注册表单创建的任何 AbstractUser 模型登录。我已经完全覆盖了UserCreationForm
上述内容,并且无法实现
get_user_model()
此错误:
AUTH_USER_MODEL refers to model 'poker.PokerUser' that has not been installed
Django 代码get_user_model()
是:
def get_user_model():
"Return the User model that is active in this project"
from django.conf import settings
from django.db.models import get_model
try:
app_label, model_name = settings.AUTH_USER_MODEL.split('.')
except ValueError:
raise ImproperlyConfigured("AUTH_USER_MODEL must be of the form 'app_label.model_name'")
user_model = get_model(app_label, model_name)
if user_model is None:
raise ImproperlyConfigured("AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL)
return user_model
由于我已经AUTH_USER_MODEL = 'poker.PokerUser'
在我的 中进行了设置settings.py
,因此应该可以。我已经通过 Django 控制台验证了这一点:
>>> from django.contrib.auth import get_user_model
>>> settings.AUTH_USER_MODEL
Out[14]: 'poker.PokerUser'
>>> from django.db.models import get_model
>>> app_label, model_name = settings.AUTH_USER_MODEL.split('.')
>>> user_model = get_model(app_label, model_name)
>>> user_model
Out[18]: poker.models.PokerUser
但是,实施仍然无法正常工作。
如果你已经读到这里,谢谢!
编辑3:
AUTH_USER_MODEL refers to model 'poker.PokerUser' that has not been installed
已修复。我不小心拥有了UserCreationForm
我重新创建的poker.models
而不是registration.forms
,所以当我运行get_user_model()
分配给 时poker.PokerUser
,它无法解析,因为它已经在那个位置。
现在剩下的唯一问题是,在创建新用户时,他们的密码不会保存。通过在此处放置打印语句,我已将其缩小为单个方法UserCreationForm
:
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
print password1
password2 = self.cleaned_data.get("password2")
print password2
if password1 and password2 and password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'])
print password2
return password2
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
print self.cleaned_data["password1"]
if commit:
user.save()
return user
print password1
andprint password1
语句中显示clean_password2
明文密码,但方法print self.cleaned_data["password1"]
中save
为空白。为什么我的表单数据没有传递给 save 方法?
TL;DR AbstractUser
模型创建在管理员和注册表单中都有效,但只有通过管理员创建的用户才能登录。通过注册表创建的用户无法登录,并且似乎在没有密码的情况下保存 - 所有其他信息都正确保存。