gpt4 book ai didi

python - Django 创建没有密码的新用户

转载 作者:行者123 更新时间:2023-11-28 21:48:11 25 4
gpt4 key购买 nike

我正在使用自定义 UserCreationForm 创建新用户,然后使用 auth.views 中的 password_reset 和自定义电子邮件模板发送注册邮件给用户。

此过程运行良好,用户能够成功完成注册过程并开始使用该应用程序。我现在想创建用户而不必为用户设置密码。

我尝试将 self.fields['password1'].requiredself.fields['password2'].required 设置为 FalseUserCreationForm 初始化方法中推荐 here但这对我没有用。不幸的是,事实证明它很难调试。我没有看到任何错误消息,但我知道没有调用 RegistrationView 注册方法。

这是我的 UserCreationForm

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

class Meta:
model = User
fields = ("email",)

def __int__(self):
self.fields['password1'].required = False
self.fields['password2'].required = False

def save(self, commit=True):
user = super(UserCreateForm, self).save(commit=False)
clean_email = self.cleaned_data["email"]
user.email = clean_email
if commit:
user.save()
custom_user = CustomUser()
custom_user.id = user
custom_user.save()
return user

这是我的 RegistrationView

class UserRegistration(RegistrationView):
def __init__(self):
self.form_class = UserCreateForm
self.success_url = 'login'
self.template_name = 'register.html'

def register(self, request, form):
new_user = form.save()

我正在使用 Django 1.8。如果有任何其他信息可以分享,请告诉我。

最佳答案

以编程方式,您可以创建/保存一个没有密码参数的新用户,它会< em>不 引发任何异常。事实上,您甚至可以在不使用任何参数的情况下创建 用户。这是解释here .

诀窍是使用 create() 而不是 create_user() ,正如所讨论的here .

例如,您可以在代码中这样做:

User.objects.create(username='user without password')

然后数据库字段password 将包含一个空字符串。因为用户现在存在,管理员将显示 UserChangeForm,密码将显示为 ReadOnlyPasswordHashField。上面写着“No password set.”,如下图所示。您可以从那里正常进行。

screenshot of admin site

请注意,此空密码unusable password 相同. PasswordResetView does not work with an unusable password ,但它确实可以使用空密码。

另请注意 User.objects.create(password='') 有效,但 User.objects.create(password=None) 无效:后者引发由于数据库中的 NOT NULL 约束导致的 IntegrityError

只是为了说明这些选项,下面是一个使用不同方式创建用户的测试:

from django.test import TestCase
from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password
import django.db
import django.db.transaction

RAW_PASSWORD = 'mypassword'


class UserTests(TestCase):
def tearDown(self) -> None:
# print passwords as stored in test database
for user in User.objects.all():
print(f'username: {user.username}\tpassword: {user.password}')

def test_user_create_missing_required_fields(self):
# none of these raise any exceptions, despite required model fields
user_kwargs = [dict(),
dict(username='a'),
dict(username='b', password=''),
dict(username='c', password=RAW_PASSWORD)]
for kwargs in user_kwargs:
user = User.objects.create(**kwargs)
# password is "usable" ...
self.assertTrue(user.has_usable_password())
if 'password' in kwargs:
# stored password is still raw (not hashed)
self.assertEqual(kwargs['password'], user.password)
# ... but password-check fails
self.assertFalse(user.check_password(kwargs['password']))

def test_user_set_password(self):
# can set a usable password after user creation
user = User(username='d')
user.set_password(RAW_PASSWORD) # does not save...
user.save()
self.assertTrue(user.has_usable_password())
self.assertNotEqual(RAW_PASSWORD, user.password)
self.assertTrue(user.check_password(RAW_PASSWORD))

def test_user_create_hashed_password(self):
# we can initialize with a hashed password
hashed_password = make_password(RAW_PASSWORD)
user = User.objects.create(username='e', password=hashed_password)
self.assertTrue(user.has_usable_password())
self.assertTrue(user.check_password(RAW_PASSWORD))

def test_user_set_unusable_password(self):
# can set an unusable password
user = User(username='f')
user.set_unusable_password() # does not save...
user.save()
self.assertFalse(user.has_usable_password())

@django.db.transaction.atomic
def test_user_create_password_none(self):
# cannot initialize with password=None (violates the NOT NULL constraint)
with self.assertRaises(django.db.IntegrityError) as a:
User.objects.create(username='g', password=None)
self.assertIn('not null', str(a.exception).lower())

def test_user_set_password_none(self):
# can set None in set_password(), but that becomes unusable
user = User(username='h')
user.set_password(None)
user.save()
self.assertFalse(user.has_usable_password())

def test_user_force_login(self):
# for testing, we can use force_login(),
# even if the user is created without arguments
user_without_args = User.objects.create()
self.client.force_login(user=user_without_args)
self.assertTrue(user_without_args.is_authenticated)

关于python - Django 创建没有密码的新用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35690022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com