django.contrib.auth.models.User

Here are the examples of the python api django.contrib.auth.models.User taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: talk.org
Source File: __init__.py
View license
def InstallAuthentication():
  logging.debug("Installing authentication framework")
  from appengine_django.auth import models as helper_models
  from django.contrib.auth import models
  models.User = helper_models.User
  models.Group = helper_models.Group
  models.Permission = helper_models.Permission
  models.Message = helper_models.Message
  from django.contrib.auth import middleware as django_middleware
  from appengine_django.auth.middleware import AuthenticationMiddleware
  django_middleware.AuthenticationMiddleware = AuthenticationMiddleware
  if VERSION >= (0, 97, None):
    from appengine_django.auth import tests
    from django.contrib.auth import tests as django_tests
    django_tests.__doc__ = tests.__doc__

Example 2

Project: tddspry
Source File: auth.py
View license
def create_user(obj, username=None, password=None, email=None, active=True,
                staff=False, superuser=False, raw=False):
    """
    Create Django user with given names or with default if absent.
    """
    user = User(username=username or USERNAME,
                email=email or EMAIL)

    user.is_active = active
    user.is_staff = staff
    user.is_superuser = superuser

    if raw:
        user.password = password or PASSWORD
    else:
        user.set_password(password or PASSWORD)

    user.save()
    return user

Example 3

Project: django-social-bookmarking
Source File: tests.py
View license
    def setUp(self):
        
        self.user = User(username="bookmark_user")
        self.user.save()
        
        self.google_test = """<a href="http://www.google.com/bookmarks/mark?op=edit&amp;bkmk=http%3A//python.org&amp;title=bookmark_user" title="Google" rel="nofollow">"""
        
        self.print_test = """<a href="javascript:window.print();" title="Print" rel="nofollow">"""

Example 4

View license
    def test_initial_fields(self):
        user = User()
        user.username = 'testuser'
        clipboard = Clipboard(owner=user)
        self.assertEquals(clipboard.owner,  user)
        self.assertEquals(clipboard.contents_json, '{}')
        self.assertEquals(clipboard.is_cut, False)
        self.assertEquals(clipboard.source_left, None)
        self.assertEquals(clipboard.source_top, None)
        self.assertEquals(clipboard.source_right, None)
        self.assertEquals(clipboard.source_bottom, None)
        self.assertEquals(clipboard.source_sheet, None)

Example 5

View license
    def test_width_and_height(self):
        user = User()
        user.username = 'testuser'
        clipboard = Clipboard(owner=user)
        clipboard.source_left = 1
        clipboard.source_top = 2
        clipboard.source_right = 3
        clipboard.source_bottom = 5
        self.assertEquals(clipboard.width, 3)
        self.assertEquals(clipboard.height, 4)

Example 6

Project: cmsplugin-rt
Source File: plugins.py
View license
    def setUp(self):
        self.super_user = User(username="test", is_staff = True, is_active = True, is_superuser = True)
        self.super_user.set_password("test")
        self.super_user.save()

        self.slave = User(username="slave", is_staff=True, is_active=True, is_superuser=False)
        self.slave.set_password("slave")
        self.slave.save()


        self.FIRST_LANG = settings.LANGUAGES[0][0]
        self.SECOND_LANG = settings.LANGUAGES[1][0]
        
        self._login_context = self.login_user_context(self.super_user)
        self._login_context.__enter__()

Example 7

Project: doac
Source File: test_authorization_token.py
View license
    def setUp(self):
        self.oclient = Client(name="Test Client",
            access_host="http://localhost/")
        self.oclient.save()

        self.scope = Scope(short_name="test", full_name="Test Scope",
            description="Scope for testing")
        self.scope.save()

        self.user = User(username="test", password="test",
            email="[email protected]")
        self.user.save()

        self.token = AuthorizationToken(client=self.oclient, user=self.user)
        self.token.save()

        self.token.scope = [self.scope]
        self.token.save()

Example 8

Project: django-emailauth
Source File: tests.py
View license
    def createActiveUser(self, username='username', email='[email protected]',
        password='password'):

        user = User(username=username, email=email, is_active=True)
        user.first_name = 'John'
        user.set_password(password)
        user.save()

        user_email = UserEmail(user=user, email=email, verified=True,
            default=True, verification_key=UserEmail.VERIFIED)
        user_email.save()
        return user, user_email

Example 9

Project: readthedocs.org
Source File: test_celery.py
View license
    def setUp(self):
        repo = make_test_git()
        self.repo = repo
        super(TestCeleryBuilding, self).setUp()
        self.eric = User(username='eric')
        self.eric.set_password('test')
        self.eric.save()
        self.project = Project.objects.create(
            name="Test Project",
            repo_type="git",
            # Our top-level checkout
            repo=repo,
        )
        self.project.users.add(self.eric)

Example 10

Project: readthedocs.org
Source File: test_privacy.py
View license
    def setUp(self):
        self.eric = User(username='eric')
        self.eric.set_password('test')
        self.eric.save()

        self.tester = User(username='tester')
        self.tester.set_password('test')
        self.tester.save()

        tasks.UpdateDocsTask.delay = mock.Mock()

Example 11

Project: django-adminactions
Source File: test_utils.py
View license
def test_get_verbose_name():
    from django.contrib.auth.models import User, Permission

    user = User()
    p = Permission()
    assert six.text_type(get_verbose_name(user, 'username')) == 'username'

    assert six.text_type(get_verbose_name(User, 'username')) == 'username'

    assert six.text_type(get_verbose_name(User.objects.all(), 'username')) == 'username'

    assert six.text_type(get_verbose_name(User.objects, 'username')) == 'username'

    assert six.text_type(get_verbose_name(User.objects, get_field_by_name(user, 'username')[0])) == 'username'

    assert six.text_type(get_verbose_name(p, 'content_type.model')) == 'python model class name'

    with pytest.raises(ValueError):
        get_verbose_name(object, 'aaa')

Example 12

Project: django-concurrency
Source File: test_issues.py
View license
    def test_identity_tag(self):
        id = next(unique_id)

        obj = ListEditableConcurrentModel(pk=id)
        self.assertTrue(re.match(r"^%s,\d+$" % id, identity(obj)))

        g = User(username='UserTest', pk=3)
        self.assertEqual(identity(g), force_text(g.pk))

Example 13

Project: django-multimail
Source File: test_email.py
View license
    def setUp(self):
        self.factory = RequestFactory()
        self.request = self.factory.get('/verify')
        u = User(username='testuser')
        u.set_password('testpassword')
        u.save()
        u = authenticate(username='testuser', password='testpassword')
        self.addr = EmailAddress(user=u, email='testemail')
        self.addr.save()

Example 14

Project: django-smuggler
Source File: test_admin.py
View license
    def setUp(self):
        staff = User(username='staff')
        staff.set_password('test')
        staff.is_staff = True
        staff.save()
        staff.user_permissions.add(
            Permission.objects.get_by_natural_key(
                'change_page', 'test_app', 'page'))
        self.url = reverse('admin:test_app_page_changelist')
        self.c = Client()
        self.c.login(username='staff', password='test')

Example 15

Project: django-smuggler
Source File: test_admin.py
View license
    def setUp(self):
        superuser = User(username='superuser')
        superuser.set_password('test')
        superuser.is_staff = True
        superuser.is_superuser = True
        superuser.save()
        self.url = reverse('admin:test_app_page_changelist')
        self.c = Client()
        self.c.login(username='superuser', password='test')

Example 16

Project: ska
Source File: tests.py
View license
    def create_admin_user():
        """
        Create a user for testing the dashboard.

        TODO: At the moment an admin account is being tested. Automated tests with diverse accounts are
        to be implemented.
        """
        u = User()
        u.username = SKA_TEST_USER_USERNAME
        u.email = '[email protected]'
        u.is_superuser = True
        u.is_staff = True
        u.set_password(SKA_TEST_USER_PASSWORD)

        try:
            u.save()
        except Exception as e:
            pass

Example 17

Project: bugle_project
Source File: tests.py
View license
    def test_in_reply_to(self):
        u = User(username='test')
        u.set_password('test')
        u.save()
        b1 = Blast.objects.create(
            user=u,
            message='Hello',
        )
        self.assertTrue(self.client.login(username='test', password='test'))
        res = self.client.post('/post/', {
            'message': 'Why hello there', 
            'in_reply_to': b1.pk
        })
        self.assertRedirects(res, '/')
        b2 = Blast.objects.order_by('-created')[0]
        self.assertNotEqual(b1, b2)
        self.assertEqual(b1.user, u)
        self.assertEqual(b2.user, u)
        self.assertEqual(b1, b2.in_reply_to)

Example 18

Project: django-loginas
Source File: tests.py
View license
def create_user(username='', password='', **kwargs):
    user = User(username=username, **kwargs)
    if password:
        user.set_password(password)
    user.save()
    return user

Example 19

Project: django-oscar-support
Source File: test_api.py
View license
    def test_display_text_including_full_name(self):
        user = User(
            email='[email protected]',
            first_name='Peter',
            last_name="Griffin"
        )
        self.assertEquals(
            self.serializer.get_display_text(user),
            'Peter Griffin <[email protected]>'
        )

Example 20

Project: django-oscar-support
Source File: test_api.py
View license
    def test_display_text_including_email_only(self):
        user = User(email='[email protected]')
        self.assertEquals(
            self.serializer.get_display_text(user),
            '[email protected]'
        )

Example 21

Project: django-formwizard
Source File: formtests.py
View license
    def test_form_instance(self):
        request = get_request()
        the_instance = User()
        testform = TestWizard.as_view([('start', UserForm), ('step2', Step2)],
            instance_dict={'start': the_instance})
        response, instance = testform(request)

        self.assertEqual(
            instance.get_form_instance('start'),
            the_instance)
        self.assertEqual(
            instance.get_form_instance('non_exist_instance'),
            None)

Example 22

Project: django-fancypages
Source File: test_container.py
View license
@pytest.fixture
def request_context():
    request = RequestFactory().get('/')
    request.fp_edit_mode = True
    request.user = User()
    return RequestContext(request, {})

Example 23

Project: open-synthesis
Source File: createadmin.py
View license
    def handle(self, *args, **options):
        """Handle the command invocation."""
        email = getattr(settings, 'ADMIN_EMAIL_ADDRESS', None)
        username = getattr(settings, 'ADMIN_USERNAME', None)
        password = getattr(settings, 'ADMIN_PASSWORD', None)

        if not email or not username or not password:
            raise CommandError('ADMIN_USERNAME, ADMIN_PASSWORD, and ADMIN_EMAIL_ADDRESS must be set')

        admin = User(username=username, email=email)
        admin.set_password(password)
        admin.is_superuser = True
        admin.is_staff = True
        admin.save()

        msg = 'Successfully configured admin %s (%s)' % (username, email)
        self.stdout.write(self.style.SUCCESS(msg))  # pylint: disable=no-member

Example 24

View license
    def test_flowurl_guess_by_task(self):
        act = TestTemplateTagsFlow.start.run()
        task = act.process.get_task(TestTemplateTagsFlow.view)
        url = Template("{% load viewflow %}{% flowurl task user=user %}").render(
            Context({'request': self.request, 'task': task, 'user': User()}))
        self.assertEqual(
            '/test/{}/view/{}/assign/'.format(act.process.pk, task.pk),
            url)

Example 25

Project: weixin2py
Source File: models.py
View license
def create_weiuser(openid, password):
    user = User()
    user.set_password(password)
    user.username = 'UnNamedUser'
    user.save()

    profile = WeixinUser()
    profile.auth_user = user
    profile.openid = openid
    profile.save()

Example 26

Project: dagny
Source File: resources.py
View license
    @action
    def update(self, user_id):
        self.user = get_object_or_404(models.User, id=int(user_id))
        self.form = forms.UserChangeForm(self.request.POST, instance=self.user)
        if self.form.is_valid():
            self.form.save()
            return redirect('User#show', str(self.user.id))

        return self.edit.render(status=403)

Example 27

Project: django-authorizenet
Source File: utils.py
View license
def create_user(id=None, username='', password=''):
    user = User(username=username)
    user.id = id
    user.set_password(password)
    user.save()
    return user

Example 28

Project: django-cart
Source File: tests.py
View license
    def _create_user_in_database(self):
        """
            Helper function so I don't repeat myself
        """ 
        user = User(username="user_for_sell", password="sold", 
                email="[email protected]")
        user.save() 
        return user

Example 29

Project: django-braces
Source File: test_forms.py
View license
    def test_with_user_kwarg(self):
        """
        Form's 'user' attribute should be set to value passed as 'user'
        argument.
        """
        user = User(username='test')
        form = forms.FormWithUserKwarg(user=user)
        assert form.user is user

Example 30

Project: django-coupons
Source File: test_forms.py
View license
    def test_user(self):
        other_user = User(username="user2")
        other_user.save()
        form_data = {'code': self.coupon.code}
        form = CouponForm(data=form_data, user=other_user)
        self.assertFalse(form.is_valid())

Example 31

Project: colab
Source File: forms.py
View license
    def create_user(self, username=None, commit=True):
        user = User()
        if username is None:
            raise NotImplementedError("SignupForm.create_user does not handle "
                "username=None case. You must override this method.")
        user.username = username
        user.email = self.cleaned_data["email"].strip().lower()
        password = self.cleaned_data["password1"]
        if password:
            user.set_password(password)
        else:
            user.set_unusable_password()
        if commit:
            user.save()
        return user

Example 32

Project: django-rulez
Source File: templatetags.py
View license
    def test_active_user_against_missing_permission(self):
        permission = "missing"
        rendered = self.render_template(
            "{% load rulez_perms %}"
            "{% rulez_perms " + permission + " object as can %}"
            "{% if can %}yes he can{% else %}no he can't{% endif %}",
            {
                "user": User(is_active=True),
                "object": MockModel()
            }
        )
        self.assertEqual(rendered, "no he can't")

Example 33

Project: Adlibre-DMS
Source File: tests.py
View license
    def setUp(self):
        # Creating a special registration user
        self.registration_email = '[email protected]'
        self.registration_username = 'RegistrationTest'
        registration_user = User(username=self.registration_username)
        registration_user.email = self.registration_email
        registration_user.save()
        self.registration_user = registration_user

Example 34

Project: avos
Source File: base.py
View license
    def test_site(self):
        self.assertEqual("Horizon", unicode(base.Horizon))
        self.assertEqual("<Site: horizon>", repr(base.Horizon))
        dash = base.Horizon.get_dashboard('cats')
        self.assertEqual(dash, base.Horizon.get_default_dashboard())
        test_user = User()
        self.assertEqual(dash.get_absolute_url(),
                         base.Horizon.get_user_home(test_user))

Example 35

Project: avos
Source File: base.py
View license
    def setUp(self):
        self.orig_user_home = settings.HORIZON_CONFIG['user_home']
        super(BaseHorizonTests, self).setUp()
        self.original_username = "testname"
        self.test_user = User()
        self.test_user.username = self.original_username

Example 36

Project: django-onetomany
Source File: tests.py
View license
    def setUp(self):
        self.u1 = User(username='user1')
        self.u1.save()
        self.u2 = User(username='user2')
        self.u2.save()
        self.u3 = User(username='user3')
        self.u3.save()
        
        self.t1 = Team(name='Team 1')
        self.t1.save()
        self.t2 = Team(name='Team 2')
        self.t2.save()

Example 37

Project: django-datagrid
Source File: tests.py
View license
    def setUp(self):
        self.old_auth_profile_module = getattr(settings, "AUTH_PROFILE_MODULE",
                                               None)
        settings.AUTH_PROFILE_MODULE = None
        populate_groups()
        self.user = User(username="testuser")
        self.request = HttpRequest()
        self.request.user = self.user
        self.datagrid = GroupDataGrid(self.request)

Example 38

Project: Django-Socialauth
Source File: auth_backends.py
View license
    def authenticate(self, github_access_token, user=None):
        response_qs = parse_qs(github_access_token)
        github_access_token = response_qs['access_token'][0]
        try:
            github_user = GithubUserProfile.objects.get(access_token=github_access_token)
            return github_user.user
        except GithubUserProfile.DoesNotExist:
            github_user_count = GithubUserProfile.objects.all().count()
            username = "GithubUser:" + str(github_user_count+1)
            user = User(username=username)
            user.save()
            github_user = GithubUserProfile(user=user, access_token=github_access_token)
            github_user.save()
            AuthMeta(user=user, provider='Github').save() 
            return github_user.user

Example 39

Project: Django-Socialauth
Source File: auth_backends.py
View license
    def authenticate(self, foursquare_access_token):
        try:
            foursquare_profile = FoursquareUserProfile.objects.get(access_token=foursquare_access_token)
            return foursquare_profile.user 
        except FoursquareUserProfile.DoesNotExist:
            foursquare_user_count = FoursquareUserProfile.objects.all().count()
            username = "FoursquareUser:" + str(foursquare_user_count+1)
            user = User(username=username)
            user.save()
            foursquare_user = FoursquareUserProfile(user=user, access_token=foursquare_access_token)
            foursquare_user.save()
            AuthMeta(user=user, provider='Foursquare').save()
            return foursquare_user.user 

Example 40

Project: sentry-old
Source File: __init__.py
View license
    def setUp(self):
        self.user = User(username="admin", email="[email protected]", is_staff=True, is_superuser=True)
        self.user.set_password('admin')
        self.user.save()
        self.client.login(username='admin', password='admin')
        
        settings.REDMINE_URL = 'http://localhost:3000'
        settings.REDMINE_PROJECT_SLUG = 'sentry'

Example 41

Project: django-socialite
Source File: backends.py
View license
    def register_user(self, access_token):
        try:
            user_info = helper.user_info(access_token)
        except: # TODO: bare except, bad!
            return None

        screen_name = ''.join((user_info['firstname'], user_info['lastname']))
        user = User(username=get_unique_username(screen_name),
                    first_name=user_info['firstname'],
                    last_name=user_info['lastname'],
                    password=hashlib.md5(str(random.random())).hexdigest())
        user.save()
        return user

Example 42

Project: django-socialite
Source File: backends.py
View license
    def register_user(self, access_token):
        try:
            user_info = helper.user_info(access_token)
        except: # TODO: bare except, bad!
            return None

        name_parts = user_info['name'].split(' ')
        if len(name_parts) > 1:
            first_name = name_parts[0]
            last_name = ' '.join(name_parts[1:])
        else:
            first_name, last_name = user_info['name'], ''
        screen_name = user_info['webUri'].split('/')[-1]
        user = User(username=get_unique_username(screen_name),
                    first_name=first_name,
                    last_name=last_name,
                    password=hashlib.md5(str(random.random())).hexdigest())
        user.save()
        return user

Example 43

Project: django-lfc
Source File: utils.py
View license
def create_request(path="/", params=None):
    """
    """
    if params is None:
        params = {}

    rf = RequestFactory()
    request = rf.get(path, params)
    request.session = SessionStore()

    user = User()
    user.is_superuser = True
    user.save()
    request.user = user

    return request

Example 44

Project: django-permissions
Source File: tests.py
View license
def create_request():
    """
    """
    rf = RequestFactory()
    request = rf.get('/')
    request.session = SessionStore()

    user = User()
    user.is_superuser = True
    user.save()
    request.user = user

    return request

Example 45

Project: django-workflows
Source File: tests.py
View license
def create_request():
    """
    """
    rf = RequestFactory()
    request = rf.get('/')
    request.session = SessionStore()

    user = User()
    user.is_superuser = True
    user.save()
    request.user = user

    return request

Example 46

Project: django-prbac
Source File: arbitrary.py
View license
def arbitrary_user(username=None, password=None, email=None, save=True, **kwargs):
    username = instantiate(username or arbitrary_unique_slug)[:74]
    password = instantiate(password or arbitrary_unique_slug)[:74]
    email = instantiate(email) if email is not None else ('%[email protected]%s.com' % (arbitrary_unique_slug(), arbitrary_unique_slug()))[:74]

    user = User(username=username,
                password=password,
                email=email,
                **kwargs)

    if save:
        user.save()

    return user

Example 47

Project: django
Source File: tests.py
View license
    def test_get_admin_log_templatetag_no_user(self):
        """
        The {% get_admin_log %} tag should work without specifying a user.
        """
        user = User(username='jondoe', password='secret', email='[email protected]')
        user.save()
        ct = ContentType.objects.get_for_model(User)
        LogEntry.objects.log_action(user.pk, ct.pk, user.pk, repr(user), 1)

        t = Template(
            '{% load log %}'
            '{% get_admin_log 100 as admin_log %}'
            '{% for entry in admin_log %}'
            '{{ entry|safe }}'
            '{% endfor %}'
        )
        self.assertEqual(t.render(Context({})), 'Added "<User: jondoe>".')

Example 48

Project: django
Source File: test_mixins.py
View license
    @mock.patch.object(models.User, 'is_authenticated', False)
    def test_stacked_mixins_not_logged_in(self):
        user = models.User.objects.create(username='joe', password='qwerty')
        perms = models.Permission.objects.filter(codename__in=('add_customuser', 'change_customuser'))
        user.user_permissions.add(*perms)
        request = self.factory.get('/rand')
        request.user = user

        view = StackedMixinsView1.as_view()
        with self.assertRaises(PermissionDenied):
            view(request)

        view = StackedMixinsView2.as_view()
        with self.assertRaises(PermissionDenied):
            view(request)

Example 49

Project: ab-kurs-kayit
Source File: coursesubops.py
View license
    @staticmethod
    def createinst(postrequest, numofinst):
        insts = []
        uprof = UserProfileOPS()
        for i in xrange(numofinst):
            n_str = str(i) + '-'
            upass = uprof.generatenewpass(10)  # uretilen parola olusturulan kullaniciya gonderilecek.
            inst = User(first_name=postrequest[n_str + 'first_name'], last_name=postrequest[n_str + 'last_name'],
                        email=postrequest[n_str + 'email'], username=postrequest[n_str + 'email'], password=upass)
            inst.save()
            instprof = UserProfile(job=postrequest[n_str + 'job'], title=postrequest[n_str + 'title'],
                                   organization=postrequest[n_str + 'organization'], is_instructor=True,
                                   user=inst)
            instprof.save()
            insts.append(instprof)
        return insts

Example 50

Project: django-lockdown
Source File: tests.py
View license
    def add_user(self, username='test', password='pw', **kwargs):
        """Add a user used for testing the auth form."""
        from django.contrib.auth.models import User
        user = User(username=username, **kwargs)
        user.set_password(password)
        user.save()