• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python models.User类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中users.models.User的典型用法代码示例。如果您正苦于以下问题:Python User类的具体用法?Python User怎么用?Python User使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了User类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: start

def start(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            # user = User.objects.create_user(
            #     username=form.cleaned_data['username'],
            #     password=form.cleaned_data['password1'],
            #     email=form.cleaned_data['email']
            # )
            user = User(username=form.cleaned_data['username'], password=form.cleaned_data['password1'], email=form.cleaned_data['email'])
            user.save()
            return HttpResponseRedirect('/users/success/')
    else:
        form = RegistrationForm()

    # 로그인 세션 확인
    # 아이디와 비밀번호 비교해서 로그인 성공 시 'login_info' 세션 생성해서 아이디 저장
    # request.session['login_info'] = "~~~id" 하고 is_login = TRUE 로 변경
    if request.session.get('login_info', False):
        is_login = True

    else:
        is_login = False

    print(is_login)

    variables = RequestContext(request, {
        'form': form,
        'is_login': is_login,
    })

    return render_to_response(
        'torch/start.html',
        variables,
    )
开发者ID:mlf23,项目名称:Torch,代码行数:35,代码来源:views.py


示例2: count

def count(request):
    msg = 'debug'
    user = User()
    if request.method == 'POST':
        username = request.POST.get('username', '')
        password = request.POST.get('password', None)
        if 'login' in request.POST:
            res = user.login(username, password)
            if res > 0:
                msg = 'Welcome %s<br>You have logged in %s times.' % (username, res)
            elif res == user.ERR_BAD_CREDENTIALS:
                msg = 'Invalid username and password combination. Please try again.'
            else:
                msg = 'An error occurred. Please try again.'
        elif 'add' in request.POST:
            res = user.add(username, password)
            if res > 0:
                msg = 'Welcome %s<br>You have logged in 1 time.' % (username)
            elif res == user.ERR_BAD_USERNAME:
                msg = 'The user name should not be empty or longer than 128 characters. Please try again.'
            elif res == user.ERR_BAD_PASSWORD:
                msg = 'The password should not be longer than 128 characters. Please try again.'
            elif res == user.ERR_USER_EXISTS:
                msg = 'This user name already exists. Please choose another one.'
            else:
                msg = 'A error occurred. Please try again.'
        return render(request, 'users/count.html', {'msg': msg})
    return HttpResponseRedirect('/client')
开发者ID:JulianJaffe,项目名称:Warmup,代码行数:28,代码来源:views.py


示例3: JWTAuthBackendTests

class JWTAuthBackendTests(TestCase):
    def setUp(self):
        self.user = User()
        self.user.username = "batman"
        self.user.email = "[email protected]"
        self.user.first_name = "Bruce"
        self.user.last_name = "Wayne"
        self.user.save()

        self.backend = JWTAuthBackend()

        self.jwt_ok = jwt_utils.create_jwt(self.user)
        self.jwt_wrong = jwt_utils.create_jwt(self.user, secret="wrong_key")

    def test_jwt_ok(self):
        request = RequestFactory().get("/something")
        request.COOKIES[settings.JWT_COOKIE_NAME] = self.jwt_ok

        result = self.backend.authenticate(request)

        self.assertEqual(self.user, result)

    def test_bad_jwt(self):
        request = RequestFactory().get("/something")
        request.COOKIES[settings.JWT_COOKIE_NAME] = self.jwt_wrong

        result = self.backend.authenticate(request)

        self.assertIsNone(result)
开发者ID:Endika,项目名称:wiggum,代码行数:29,代码来源:test_backends.py


示例4: unitTests

def unitTests(request):
    """Runs all the unit tests and returns a json object with the total number of tests run, their
    output, and the number of failed tests."""
    user = User()
    res = user.unitTests()
    result = {'nrFailed': res[0], 'output': res[1], 'totalTests': res[2]}
    return HttpResponse(json.dumps(result), content_type="application/json")
开发者ID:JulianJaffe,项目名称:Warmup,代码行数:7,代码来源:views.py


示例5: register

def register():
    form = RegisterForm(request.form)
    if form.validate_on_submit():
        # Create new User instance
        user = User(
            name=form.username.data,
            email=form.email.data,
            password=form.password.data,
        )

        try:
            user.save()
        except UniquenessViolation, err:
            if err.column_name == "email":
                form.email.errors.append("There is already an account registered with that email address.")
            elif err.column_name == "name":
                form.username.errors.append("There is already an account registered with that username.")
        else:
            login_user(user)

            # Flash a message that gets displayed only once.
            flash("Welcome to the herd.")

            return redirect(url_for("users.profile"))
        finally:
开发者ID:shunyata,项目名称:nobooru,代码行数:25,代码来源:views.py


示例6: clean_email

 def clean_email(self):
   email = self.cleaned_data["email"]
   try:
     User.get(email=email)
   except UserDoesNotExist:
     return email
   raise forms.ValidationError(_("A user with that email already exists."))
开发者ID:zerofuxor,项目名称:ContentQ-CMS,代码行数:7,代码来源:forms.py


示例7: save_model

	def save_model(self, request, obj, form, change):
		old_obj = None
		cur_email = None
		try:		
			old_obj = Judge.objects.get(pk=obj.id)			
			cur_email = old_obj.email

		except ObjectDoesNotExist:
			pass
		
		new_obj = form.save(commit=False)
		new_email = new_obj.email

		try:
			user = User.objects.get(email=cur_email)
			user.name = new_obj.name
			user.email = new_obj.email
			user.organisation = new_obj.organisation
			user.save()	
		except ObjectDoesNotExist:
			#Does not exist, Add
			password = str(hashlib.sha1(new_obj.email).hexdigest())[:20]
			user = User(name=new_obj.name,email=new_obj.email,organisation=new_obj.organisation,date_registration=datetime.now(),category=USER_JUDGE,password=password)
			user.save()
			#Send mail
		
		obj.save()
开发者ID:EDCIITR,项目名称:EDC-Website,代码行数:27,代码来源:admin.py


示例8: RateViewTests

class RateViewTests(TestCase):
    def setUp(self):
        self.book = Book(isbn='85-359-0277-5', title='title', price=10, author='author',
                    image='test.jpg')
        self.book.save()
        self.user = User(user_id=1, name='test')
        self.user.save()
        self.book2 = Book(isbn='0-306-40615-2', title='title', price=10, author='author',
                    image='test.jpg')
        self.book2.save()
        rate = Rate(rating=1, book_id=self.book2, user_id=self.user)
        rate.save()

    def test_put_new_rate_should_return_201(self):
        """
        When non existing rate, new one is added
        """
        resp = self.client.put('/ebucxop/books/85-359-0277-5/ratings/me?format=json', {'rating': 3},
                    HTTP_AUTHORIZATION='Basic ' + base64.b64encode('%s:%s' % ('Aladdin', 'open sesame')))
        response_content = json.loads(resp.content)
        self.assertEqual(resp.status_code, 201)
        self.assertEquals('3', response_content['rating'])

    def test_put_existing_rate_should_return_200(self):
        """
        When existing rate, old rate is updated and 200 returned
        """
        resp = self.client.put('/ebucxop/books/0-306-40615-2/ratings/me?format=json', {'rating': u'3'},
                    HTTP_AUTHORIZATION='Basic ' + base64.b64encode('%s:%s' % ('Aladdin', 'open sesame')))
        self.assertEqual(resp.status_code, 200)
        response_content = json.loads(resp.content)
        # Ensure that 1 is changed to 3
        self.assertEquals('3', response_content['rating'])
开发者ID:ealogar,项目名称:tdaf-ebooks.python,代码行数:33,代码来源:tests_book_views.py


示例9: AdminAuthorizationRedirectMiddlewareTests

class AdminAuthorizationRedirectMiddlewareTests(TestCase):
    def setUp(self):
        self.factory = RequestFactory()
        self.middleware = AdminAuthorizationRedirectMiddleware()

        self.user = User()
        self.user.username = "batman"
        self.user.email = "[email protected]"
        self.user.first_name = "Bruce"
        self.user.last_name = "Wayne"
        self.user.save()

    def test_not_admin_url(self):
        request = RequestFactory().get("/something")
        result = self.middleware.process_request(request)

        self.assertIsNone(result)

    def test_admin_url_user_not_staff(self):
        request = RequestFactory().get(reverse("admin:index"))
        request.user = self.user
        result = self.middleware.process_request(request)

        self.assertEqual(settings.ADMIN_UNATHORIZED_REDIRECTION_URL, result.url)
        self.assertTrue(isinstance(result, HttpResponseRedirect))

    def test_admin_url_user_staff(self):
        adm = User.objects.create_superuser(username="batmanadmin",
                                            email="[email protected]")
        request = RequestFactory().get(reverse("admin:index"))
        request.user = adm
        result = self.middleware.process_request(request)

        self.assertIsNone(result)
开发者ID:Endika,项目名称:wiggum,代码行数:34,代码来源:test_middleware.py


示例10: delete_users

def delete_users():
    """
    delete all users from database

    """
    from users.models import User
    User.objects().delete()
开发者ID:g13013,项目名称:dzlibs,代码行数:7,代码来源:manage.py


示例11: generate_users

def generate_users(mask, info):
    for index, username in info:
        login = mask % index
        password = User.objects.make_random_password()
        user = User(login=login, username=username, rights=0x0)
        user.set_password(password)
        yield user, password
开发者ID:SoVictor,项目名称:Lerna,代码行数:7,代码来源:genusers.py


示例12: saveNewUser

def saveNewUser(username, password):
    newuser = User(
            username = username,
            password = password,
        )
    newuser.save()
    return newuser
开发者ID:dkroyalty,项目名称:pythonProjs,代码行数:7,代码来源:views.py


示例13: test_update_password

    def test_update_password(self):
        user1 = User(username='user1')
        user1.set_password('12345')
        user1.save()
        update_data = {
            'password': 'abcde',
        }

        request = self.request_factory.patch(reverse('users:user-detail', kwargs={'pk': 1}), update_data, format='json')
        force_authenticate(request, user=user1)
        view = UserDetail.as_view()
        response = view(request, pk=1)
        response.render()

        self.assertEqual(response.status_code, status.HTTP_200_OK)

        # We confirmed that the update response worked, so let's test the new password in authentication
        update_data = {
            'username': user1.username,
            'password': 'abcde',
        }
        request = self.request_factory.post(reverse('auth:token'), update_data, format='json')
        view = ObtainJSONWebToken.as_view()
        response = view(request)
        response.render()

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertTrue(response.data.get('token'))
开发者ID:KTruong888,项目名称:resources,代码行数:28,代码来源:test_views.py


示例14: addUser

def addUser(request):
    form = UserForm(request.POST)
    
    if form.is_valid():
        try:
            with transaction.atomic():
                enterprise = Enterprise()
                enterprise.save()
                request.session['idEnterprise'] = enterprise.id;
                
                location= Location(enterprise=enterprise, lat=0, lng=0, name='Main Office')
                location.save()
                
                user = User(location = location, email=form.cleaned_data['email'], 
                        password=form.cleaned_data['password'])
                user.save()
                request.session['idUser'] = user.id;
                
                profile = Profile(user = user, role="Administrator")
                profile.save()
                
                return render(request, 'users/dashboard.html')
                
        except Exception as e:
            print(e)
            messages.error(request, 'Sorry, Internal Error')
                
    else:
        messages.error(request, 'Please fill the form')
        return HttpResponseRedirect('/signup')
开发者ID:edramos,项目名称:path00,代码行数:30,代码来源:views.py


示例15: test_refresh_token

	def test_refresh_token( self, token_delete, token_save ):
		user = User( pk=1, username='test' )
		user.token = Token_factory.build()
		token = user.refresh_token()
		user.token.delete.assert_not_called()
		token_save.assert_not_called()
		self.assertEqual( token.user.pk, user.pk )
开发者ID:dem4ply,项目名称:yacatecuhtli,代码行数:7,代码来源:user.py


示例16: register

def register(request):
    if request.method == 'POST':
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        password2 = request.POST.get('password2', '')
        if not re.match(r'^\w{5,}$', username):
            error = 'invalid_username'
        elif len(password) < 5:
            error = 'invalid_password'
        elif password != password2:
            error = 'password_mismatch'
        else:
            try:
                User.create(username, password)
            except IntegrityError:
                error = 'username_taken'
            else:
                return HttpResponseRedirect("/")
    else:
        error = ''
        username = ''

    return render(request, "register.html", {
        'error': error,
        'username': username
    })
开发者ID:savix,项目名称:jnp3,代码行数:26,代码来源:views.py


示例17: test_chg_pwd

 def test_chg_pwd(self):
     self.assertIsNone(
         User.register(None, '[email protected]', 'abc', 'abc', 'first', 'last'),
         'About to test changing of passwords'
     )
     user = User.all().filter('email =', '[email protected]').get()
     self.assertIsNotNone(user)
     self.assertIsNotNone(
         user.chgpwd('wrong', 'good', 'good'),
         'Wrong original password'
     )
     self.assertIsNotNone(
         user.chgpwd('abc', 'blah', 'different'),
         'Passwords differ'
     )
     self.assertIsNone(
         User.authenticate(None, '[email protected]', 'abc'),
         'Password should not have changed'
     )
     self.assertIsNone(
         user.chgpwd('abc', 'newpwd', 'newpwd'),
         'Valid change of password'
     )
     self.assertIsNone(
         User.authenticate(None, '[email protected]', 'newpwd'),
         'Password should have changed'
     )
     self.assertIsNotNone(user.chgpwd(None, None, None))
开发者ID:matts1,项目名称:MajorWork-appengine,代码行数:28,代码来源:tests.py


示例18: test_duplicate_add

 def test_duplicate_add(self):
     """
     Tests the add method of the User class for adding duplicate users
     """
     User.add("xxxxxx", "xxxxxx")
     result = User.add("xxxxxx", "password")
     self.assertEqual(result, ERR_USER_EXISTS)
开发者ID:flawedmatrix,项目名称:warmup,代码行数:7,代码来源:tests.py


示例19: AdminBookViewTests

class AdminBookViewTests(TestCase):
    def setUp(self):
        self.bookData = {'isbn': '85-359-0277-5', 'title': 'title', 'price': '10', 'author': 'author',
                    'image': 'test.jpg'}
        # We put user_id 2 as this would be the identifier of admin returned by TDA
        self.user = User(user_id=2, name='admin')
        self.user.save()
        self.book2 = Book(isbn='0-306-40615-2', title='title', price=10, author='author',
                    image='test.jpg')
        self.book2.save()

    def test_create_new_book_return_201(self):
        resp = self.client.post('/ebucxop/books/', data=self.bookData,
                HTTP_AUTHORIZATION='Basic ' + base64.b64encode('%s:%s' % ('admin', 'admin')))
        self.assertEqual(resp.status_code, 201)
        self.assertEquals('85-359-0277-5', resp.data['isbn'])

    def test_update_existing_book_return_200(self):
        resp = self.client.post('/ebucxop/books/0-306-40615-2/', data={'title': 'titleUpdated'},
                HTTP_AUTHORIZATION='Basic ' + base64.b64encode('%s:%s' % ('admin', 'admin')))
        self.assertEqual(resp.status_code, 200)
        self.assertEquals('titleUpdated', resp.data['title'])

    def test_create_new_book_without_credentials_return_403(self):
        resp = self.client.post('/ebucxop/books/', data=self.bookData,
                HTTP_AUTHORIZATION='Basic ' + base64.b64encode('%s:%s' % ('Aladdin', 'open sesame')))
        self.assertEqual(resp.status_code, 403)
开发者ID:ealogar,项目名称:tdaf-ebooks.python,代码行数:27,代码来源:tests_book_views.py


示例20: setUp

    def setUp(self):

        # User 1 (can impersonate user 2)
        self.user = User(username="dark-knight4",
                         email="[email protected]",
                         first_name="Bruce",
                         last_name="Wayne")
        self.user.save()
        self.user_password = "dark_knight_password"
        self.user.set_password(self.user_password)
        self.user.save()
        p = ProjectPermission.objects.get(key=settings.APP_PERMISSION_KEYS['impersonate'])
        self.user.project_permissions.add(p)
        self.user.save()

        # User 2 (can't impersonate user 1)
        self.user2 = User(username="spiderman1",
                                      email="[email protected]",
                                      first_name="Peter",
                                      last_name="Parker")
        self.user2.save()
        self.user2_password = "spiderman_password"
        self.user2.set_password(self.user2_password)
        self.user2.save()

        # Urls
        self.login_url = reverse("auth:login")
        self.impersonate_user1_url = reverse("auth:impersonate",
                                             args=[self.user.id])
        self.impersonate_user2_url = reverse("auth:impersonate",
                                             args=[self.user2.id])
开发者ID:Endika,项目名称:wiggum,代码行数:31,代码来源:test_views.py



注:本文中的users.models.User类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python models.UserNotification类代码示例发布时间:2022-05-27
下一篇:
Python models.Setting类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap