本文整理汇总了Python中accounts.models.User.set_password方法的典型用法代码示例。如果您正苦于以下问题:Python User.set_password方法的具体用法?Python User.set_password怎么用?Python User.set_password使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类accounts.models.User
的用法示例。
在下文中一共展示了User.set_password方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_user
# 需要导入模块: from accounts.models import User [as 别名]
# 或者: from accounts.models.User import set_password [as 别名]
def create_user():
try:
username = raw_input("Username: ").strip()
email = raw_input("Email: ").strip()
while True:
password = getpass("Password: ")
password_confirm = getpass(" (confirm): ")
if password_confirm == password:
break
else:
print("Passwords do not match... Try again...")
u = User(username=username)
u.email = email
# check for org
org = Organization.get_by_name("default")
if not org:
org = Organization()
org.name = "default"
org.owner = u.uuid
org.save()
u.organization = Organization.get_by_name("default").uuid
u.set_password(password)
u.add_role("admin")
u.save()
print("User created/updated successfully...")
except KeyboardInterrupt:
pass
示例2: create_user
# 需要导入模块: from accounts.models import User [as 别名]
# 或者: from accounts.models.User import set_password [as 别名]
def create_user(username=None, email=None, password=None):
u = User()
u.username = username
u.email = email
u.set_password(password)
u.save()
return True
示例3: save
# 需要导入模块: from accounts.models import User [as 别名]
# 或者: from accounts.models.User import set_password [as 别名]
def save(self, commit=True):
# Save the provided password in hashed format
User = super(UserCreationForm, self).save(commit=False)
User.set_password(self.cleaned_data["password1"])
if commit:
User.save()
return User
示例4: UserLoginTestCase
# 需要导入模块: from accounts.models import User [as 别名]
# 或者: from accounts.models.User import set_password [as 别名]
class UserLoginTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.test_user_password = "password"
self.test_user = User(email="[email protected]")
self.test_user.set_password(self.test_user_password)
self.test_user.save()
self.access_token = Token(token="test_access_token")
self.test_user.token_set.add(self.access_token)
def test_user_login_with_valid_credentials(self):
post_data = {
'email': "[email protected]",
'password': "password",
}
resp = self.client.post('/users/login/',
data=json.dumps(post_data),
content_type='application/json')
resp_data = json.loads(resp.content)
self.assertEqual(200, resp.status_code)
self.assertEqual("test_access_token", resp_data['access_token'])
def test_user_login_with_bad_password(self):
post_data = {
'email': "[email protected]",
'password': "badpassword",
}
resp = self.client.post('/users/login/',
data=json.dumps(post_data),
content_type='application/json')
self.assertEqual(404, resp.status_code)
示例5: post
# 需要导入模块: from accounts.models import User [as 别名]
# 或者: from accounts.models.User import set_password [as 别名]
def post(self, request):
form = RegistrationForm(data=request.POST)
response = HttpResponseRedirect('/')
if form.is_valid():
user = User()
year = request.POST['birthdate_year']
month = request.POST['birthdate_month']
day = request.POST['birthdate_day']
date_of_birth = year+'-'+month+'-'+day
user.birthday = date_of_birth
user.email = form.cleaned_data['email']
user.role = 'client'
user.first_name = form.cleaned_data['first_name']
user.phone_number = ''
user.zip_code = form.cleaned_data['zip_code']
user.last_name = form.cleaned_data['last_name']
user.set_password(form.cleaned_data['password'])
user.save()
confirm_register_mail(request, user.email, user.first_name, user.last_name, user.zip_code)
new_user = authenticate(email=form.cleaned_data['email'],
password=form.cleaned_data['password'],
)
login(request, new_user)
messages.success(request, "You have registered successfully.")
else:
response.set_cookie('registr_error', 'error')
cache.set('registartion_error', RegistrationForm(request.POST))
return response
示例6: UserTestCase
# 需要导入模块: from accounts.models import User [as 别名]
# 或者: from accounts.models.User import set_password [as 别名]
class UserTestCase(GraphQLTest):
def setUp(self):
self.maxDiff = None
self.user = User(
username='alisson',
email='[email protected]'
)
self.user.set_password('patricio')
self.user.save(request=None)
self.user_2 = User(
username='lanna',
email='[email protected]'
)
self.user_2.set_password('patricia')
self.user_2.save(request=None)
def _do_login(self, username='alisson', password='patricio'):
response = self.graphql({
'query': '''
mutation M($auth: AuthenticateInput!) {
authenticate(input: $auth) {
clientMutationId,
viewer {
me {
username
isAuthenticated
}
}
}
}
''',
'variables': {
'auth': {
'clientMutationId': 'mutation2',
'username': username,
'password': password,
}
}
})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), {
'data': {
'authenticate': {
'viewer': {
'me': {
'username': username,
'isAuthenticated': True
},
},
'clientMutationId': 'mutation2'
},
}
})
self.assertTrue('sessionid' in response.cookies)
return response
def _do_login_2(self, username='lanna', password='patricia'):
return self._do_login(username, password)
示例7: create_comment
# 需要导入模块: from accounts.models import User [as 别名]
# 或者: from accounts.models.User import set_password [as 别名]
def create_comment(self, username='', password='', title='', comment=''):
user = User(username=username)
user.set_password(password)
user.save()
daily = Daily.objects.create(user=user, title=title)
daily.save()
comment = Comment.objects.create(user=user, daily=daily, comment=comment)
comment.save()
示例8: create
# 需要导入模块: from accounts.models import User [as 别名]
# 或者: from accounts.models.User import set_password [as 别名]
def create(self, validated_data):
user = User()
user.set_password(validated_data["password"])
user.email = validated_data['email']
user.first_name = validated_data['first_name']
user.last_name = validated_data['last_name']
user.phone_number = validated_data['phone_number']
return user
示例9: import_users
# 需要导入模块: from accounts.models import User [as 别名]
# 或者: from accounts.models.User import set_password [as 别名]
def import_users(self):
cols = [
'id',
'jabber',
'url',
'signatura',
'nick',
'heslo',
'email',
'zobrazit_mail',
'prava',
'lastlogin',
'more_info',
'info',
'rok',
'real_name',
]
self.cursor.execute('SELECT COUNT(*) FROM users WHERE prava > 0')
self.logger.set_sub_progress(u"Užívatelia", self.cursor.fetchall()[0][0])
self.cursor.execute('SELECT ' + (', '.join(cols)) + ' FROM users WHERE prava > 0')
user_objects = []
for user in self.cursor:
self.logger.step_sub_progress()
user_dict = self.decode_cols_to_dict(cols, user)
user = {
'pk': user_dict['id'],
'username': user_dict['nick'][:30],
'email': user_dict['email'][:75],
'password': user_dict['heslo'],
'is_active': False,
'last_login': self.first_datetime_if_null(user_dict['lastlogin']),
'jabber': self.empty_if_null(user_dict['jabber']),
'url': self.empty_if_null(user_dict['url']),
'signature': self.empty_if_null(user_dict['signatura']),
'display_mail': self.empty_if_null(user_dict['zobrazit_mail']),
'distribution': self.empty_if_null(user_dict['more_info']),
'info': self.empty_if_null(user_dict['info']),
'year': user_dict['rok'],
}
if user_dict['real_name']:
space_pos = user_dict['real_name'].find(' ')
if space_pos == -1:
user['first_name'] = user_dict['real_name']
else:
user['first_name'] = user_dict['real_name'][:space_pos]
user['last_name'] = user_dict['real_name'][space_pos + 1:]
if user_dict['prava'] > 0:
user['is_active'] = True
if user_dict['prava'] > 1:
user['is_staff'] = True
if user_dict['prava'] > 2:
user['is_superuser'] = True
user_object = User(**user)
user_object.set_password(user['password'])
user_objects.append(user_object)
User.objects.bulk_create(user_objects)
connections['default'].cursor().execute('SELECT setval(\'auth_user_id_seq\', (SELECT MAX(id) FROM auth_user) + 1);')
self.logger.finish_sub_progress()
示例10: create_user
# 需要导入模块: from accounts.models import User [as 别名]
# 或者: from accounts.models.User import set_password [as 别名]
def create_user():
user = User()
user.username = request.form.get('username', None)
user.first_name = request.form.get('first_name', '')
user.last_name = request.form.get('last_name', '')
user.email = request.form.get('email', '')
user.account = request.form.get('account', None)
user.set_password(request.form.get('password', ''))
user.save()
return redirect(url_for('accounts.users'))
示例11: _user_from_ldap
# 需要导入模块: from accounts.models import User [as 别名]
# 或者: from accounts.models.User import set_password [as 别名]
def _user_from_ldap(self, entity, password=None):
is_new = False
try:
user = User.objects.get(username=entity["uid"][0])
except User.DoesNotExist:
is_new = True
user = User(username=entity["uid"][0])
user.is_staff = True
user.is_superuser = False
user.save()
if password and user.check_password(password) is False:
user.set_password(password)
user.is_staff = True
for k, kmap in (
("first_name", "givenName"),
("last_name", "sn"),
("email", "mail"),
("gid", "gidnumber"),
("uid", "uidnumber"),
("date_joined", "whencreated"),
("country", "co"),
("department", "department"),
("photo", "thumbnailphoto"),
):
if k == "date_joined":
val = datetime.strptime(entity.get(kmap)[0][:-3], "%Y%m%d%H%M%S")
elif k == "photo" and is_new == True:
photo_data = entity.get(kmap)[0]
photo_io_origin = StringIO(photo_data)
photo_img = Image.open(photo_io_origin)
photo_side = min(photo_img.size)
photo_croped = photo_img.crop((0, 0, photo_side, photo_side))
photo_croped.thumbnail(settings.THUMBNAIL_SIZE_HEAD, Image.ANTIALIAS)
photo_io_processed = StringIO()
photo_croped.save(photo_io_processed, 'png')
photo_io_origin.close()
photo_io_processed.seek(0)
val = InMemoryUploadedFile(
photo_io_processed,
None,
"{0}_{1}.png".format(user.first_name.lower(), user.last_name.lower()),
"image/png",
len(photo_data),
None
)
else:
val = entity.get(kmap)[0]
if not val:
continue
setattr(user, k, val)
user.save()
return user
示例12: test_creating_new_user
# 需要导入模块: from accounts.models import User [as 别名]
# 或者: from accounts.models.User import set_password [as 别名]
def test_creating_new_user(self):
user = User()
user.username = "test"
user.email = "[email protected]"
user.set_password("test")
user.full_clean()
user.save()
all_users = User.objects.all()
self.assertEqual(len(all_users), 1)
user_from_database = all_users[0]
self.assertEquals(user_from_database, user)
示例13: test_duplicate_email_check
# 需要导入模块: from accounts.models import User [as 别名]
# 或者: from accounts.models.User import set_password [as 别名]
def test_duplicate_email_check(self):
user = User()
user.username = "test"
user.email = "[email protected]"
user.set_password("test")
user.full_clean()
user.save()
with self.assertRaises(ValidationError):
user2 = User()
user2.username = "test2"
user2.email = "[email protected]"
user2.set_password("test")
user2.full_clean()
user2.save()
示例14: create_user_by_model
# 需要导入模块: from accounts.models import User [as 别名]
# 或者: from accounts.models.User import set_password [as 别名]
def create_user_by_model(self, **user_data):
"""
Create User instance directly, by User model.
"""
user = User(**user_data)
try:
user.full_clean()
except ValidationError as exc:
raise AssertionError(
_(u'User saving error: %s' % str(exc)))
else:
if 'password' in user_data:
user.set_password(user_data['password'])
user.save()
return user
示例15: handle
# 需要导入模块: from accounts.models import User [as 别名]
# 或者: from accounts.models.User import set_password [as 别名]
def handle(self, *args, **options):
print('Starting...')
print('======= SUMMARY =======')
with open(options['filepath'], 'r') as f:
reader = smartcsv.reader(f, columns=CSV_STRUCTURE)
counter = 0
for row in reader:
user = User(**row)
# generate random password
password = self.get_random_passwd()
user.set_password(password)
user.save()
print('{}\t{}'.format(user.username, password))
counter += 1
print('=======================')
print('Finished creating {} users.'.format(counter))