本文整理汇总了Python中accounts.models.User类的典型用法代码示例。如果您正苦于以下问题:Python User类的具体用法?Python User怎么用?Python User使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了User类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: getUserProjectTestCase
class getUserProjectTestCase(TestCase):
def setUp(self):
#initial information into temperory database
self.user = User()
self.user.username = "Bob"
self.user.password = "123"
self.user.email = "asfja"
self.user.is_confirmed = True
self.user.save()
self.emptyProjectUser = User()
self.emptyProjectUser.username = "empty"
self.emptyProjectUser.password = "123"
self.emptyProjectUser.email = "1312"
self.emptyProjectUser.is_confirmed = False
self.emptyProjectUser.save()
self.project1 = project()
self.project1.project_name = "project1"
self.project1.creator = self.user
self.project1.save()
self.project2 = project()
self.project2.project_name = "project2"
self.project2.creator = self.user
self.project2.save()
def test_normal(self):
self.assertTrue(getUserProject(self.user)['isSuccessful'])
def test_empty_project(self):
self.assertEqual(getUserProject(self.emptyProjectUser)['projects'],[])
示例2: save
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
示例3: setUp
def setUp(self):
# Create client and data for new user
self._client = APIClient()
self._admin = User(**ADMIN_USER_DATA)
self._admin.set_password(ADMIN_USER_DATA['password'])
self._admin.save()
self._user = User(**NEW_USER_DATA)
self._user.set_password(NEW_USER_DATA['password'])
self._user.save()
self._client.login(email=ADMIN_USER_DATA['email'],
password=ADMIN_USER_DATA['password'])
create_url = reverse('person-list')
self._data = NEW_PERSON_DATA.copy()
self._data['user'] = self._user.pk
response = self._client.post(create_url, self._data,
format='json')
try:
self._content_data = json.loads(response.content)
except ValueError:
raise AssertionError(
_(u'Invalid response content format, not a JSON'))
self._person_id = self._content_data.get('id')
if not self._person_id:
raise AssertionError(_(u'Not a Person ID in data'))
示例4: update_user
def update_user(self, user: User, user_information: dict):
if user_information:
user.update(
email=user_information['email'],
lastname=user_information['last_name'],
firstname=user_information['first_name']
)
示例5: saveChainTestCase
class saveChainTestCase(TestCase):
def setUp(self):
#initial information into temperory database
self.user = User()
self.user.username = "Bob"
self.user.password = "123"
self.user.email = "email"
self.user.is_confirmed = True
self.user.save()
self.project = project()
self.project.project_name = "project"
self.project.creator = self.user
self.project.save()
self.chain1 = chain()
self.chain1.name = "chain1"
self.chain1.id = 1
self.chain1.sequence = "1_2_3"
self.chain1.project = self.project
self.chain1.save()
self.client = Client()
def test_chainId_not_exist(self):
self.saveResponse = self.client.post('/home/updateChain',{'chain':'1_2','id':3})
self.realResult = JSONDecoder().decode(self.saveResponse.content)
self.assertEqual(self.realResult['isSuccessful'],False)
def test_chainId_exist(self):
self.saveResponse = self.client.post('/home/updateChain',{'chain':'1_2','id':1})
self.realResult = JSONDecoder().decode(self.saveResponse.content)
self.assertEqual(self.realResult['isSuccessful'],True)
示例6: handle
def handle(self, *args, **options):
poll_object = json.load(options['file'])
poll = VotingPoll(
title=options['title'],
description=options['description'],
admin=WhaleUser.objects.get(id=options['user_id']),
preference_model=poll_object['preferenceModel']['id'],
closing_date = date.today()
)
poll.save()
self.stdout.write(self.style.SUCCESS('Successfully created poll "%s"' % poll.id))
candidates = []
for c in poll_object['candidates']:
candidates.append(Candidate(
poll=poll,
candidate=c))
candidates[-1].save()
self.stdout.write(self.style.SUCCESS('Successfully added %d candidates' % len(candidates)))
for v in poll_object['votes']:
voter = User(nickname=v['name'])
voter.save()
for i, sc in enumerate(v['values']):
VotingScore(
candidate=candidates[i],
voter=voter,
value=sc).save()
self.stdout.write(self.style.SUCCESS('Successfully added %d votes' % len(poll_object['votes'])))
示例7: UserLoginTestCase
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)
示例8: formatProjectListTestCase
class formatProjectListTestCase(TestCase):
def setUp(self):
#initial information into temperory database
self.user = User()
self.user.username = "Bob"
self.user.password = "123"
self.user.email = "asfja"
self.user.is_confirmed = True
self.user.save()
self.project1 = project()
self.project1.project_name = "project1"
self.project1.creator = self.user
self.project1.save()
self.project2 = project()
self.project2.project_name = "project2"
self.project2.creator = self.user
self.project2.save()
def test_list_exist(self):
self.projectList = project.objects.filter(creator=self.user, is_deleted=False)
# construct the predict result
#print formatProjectList(self.projectList)
self.predictResult = list()
self.p1 = {
'id':1L,
'name':unicode(self.project1.project_name,"utf-8"),
'creator':unicode(self.user.username,"utf-8"),
'function':None,
'track':None,
}
示例9: create_comment
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()
示例10: import_users
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()
示例11: save
def save(self, email):
name = self.name.data
username = self.username.data
password = self.password.data
email = email
user = User(name=name, username=username, password=password, email=email)
user.save()
return user
示例12: create_user
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'))
示例13: create_user
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
示例14: authenticate
def authenticate(self, openid_key, request):
steamid64 = openid_key.split("/")[-1]
try:
user = User.objects.get(steam_id = steamid64)
# TODO schedule webapi call
except User.DoesNotExist:
user = User()
user.steam_id = steamid64
user.save()
# TODO force synchronous webapi call
return user
示例15: post
def post(self):
context = self.get_context()
form = context.get('login_user_form')
if form.validate():
try:
user = User.objects.get(email=form.email.data)
except DoesNotExist:
user = User(email=form.email.data)
if 'X-Forwarded-For' in request.headers:
remote_addr = request.headers.getlist("X-Forwarded-For")[0].rpartition(' ')[-1]
else:
remote_addr = request.remote_addr or 'untrackable'
old_current_login, new_current_login = user.current_login_at, datetime.utcnow()
old_current_ip, new_current_ip = user.current_login_ip, remote_addr
user.last_login_at = old_current_login or new_current_login
user.current_login_at = new_current_login
user.last_login_ip = old_current_ip or new_current_ip
user.current_login_ip = new_current_ip
user.login_count = user.login_count + 1 if user.login_count else 1
user.save()
login_user(user)
flash("Logged in user")
return redirect(url_for('pages.home'))
else:
flash_errors(form)
return render_template('home.html', **context)