Python django.contrib.auth 模块,get_user() 实例源码

我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用django.contrib.auth.get_user()

项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def logout(self):
        """
        Removes the authenticated user's cookies and session object.

        Causes the authenticated user to be logged out.
        """
        from django.contrib.auth import get_user, logout

        request = HttpRequest()
        engine = import_module(settings.SESSION_ENGINE)
        if self.session:
            request.session = self.session
            request.user = get_user(request)
        else:
            request.session = engine.SessionStore()
        logout(request)
        self.cookies = SimpleCookie()
项目:SPBU-DBMS-Project    作者:Betekhtin    | 项目源码 | 文件源码
def login(request):
    username = auth.get_user(request).username
    if (username):
        return redirect('/')
    else:
        args = {}
        args.update(csrf(request))
        if request.POST:
            username = request.POST.get('username','')
            password = request.POST.get('password','')
            user = auth.authenticate(username=username, password=password)
            if user is not None:
                if not request.POST.get('remember-me', ''):
                    request.session.set_expiry(0)
                auth.login(request, user)
                return redirect('/')
            else:
                args['login_error'] = format_html("<div class=\"main-error alert alert-error\">???????????? ??? ???????????? ??? ??????</div>")
                return render_to_response('login.html', args)
        else:
            return render_to_response('login.html', args)
项目:SPBU-DBMS-Project    作者:Betekhtin    | 项目源码 | 文件源码
def history(request):
    username = auth.get_user(request).username
    if (username):
        ?t = city.objects.all().values()
        co = country.objects.all().values()

        city_json = json.dumps(list(?t), cls=DjangoJSONEncoder,ensure_ascii=False)
        country_json = json.dumps(list(co), cls=DjangoJSONEncoder,ensure_ascii=False)
        args={}
        args['city']=city_json
        args['country'] = country_json
        args['max_date'] = []
        for i in ?t:
            args['max_date'].append((temperature.objects.filter(city_id__exact=i['city_id']).latest('date').date))
        return render_to_response("history.html",args)
    else:
        return redirect("/login")
项目:SPBU-DBMS-Project    作者:Betekhtin    | 项目源码 | 文件源码
def register(request):
    username = auth.get_user(request).username
    if not (username):
        args={}
        args.update(csrf(request))
        args['form']=UserCreationForm()
        if request.POST:
            newuser_form=UserCreationForm(request.POST)
            if newuser_form.is_valid():
                newuser_form.save()
                newuser = auth.authenticate(username=newuser_form.cleaned_data['username'],password=newuser_form.cleaned_data['password2'])
                auth.login(request, newuser)
                return redirect('/')
            else:
                args['errors'] = format_html('<div class="main-error alert alert-error">?????? ??? ???????????</div>')
                args['form'] = newuser_form
        return render_to_response('register.html',args)
    else:
        return redirect('/')
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def logout(self):
        """
        Removes the authenticated user's cookies and session object.

        Causes the authenticated user to be logged out.
        """
        from django.contrib.auth import get_user, logout

        request = HttpRequest()
        engine = import_module(settings.SESSION_ENGINE)
        if self.session:
            request.session = self.session
            request.user = get_user(request)
        else:
            request.session = engine.SessionStore()
        logout(request)
        self.cookies = SimpleCookie()
项目:channels-obstruction    作者:codyparker    | 项目源码 | 文件源码
def dispatch(self, request, *args, **kwargs):
        # get the game by the id
        self.game = Game.get_by_id(kwargs['game_id'])
        user = get_user(request)
        # check to see if the game is open and available for this user
        # if this player is the creator, just return
        if self.game.creator == user or self.game.opponent == user:
            return super(GameView, self).dispatch(request, *args, **kwargs)

        # if there is no opponent and the game is not yet completed,
        # set the opponent as this user
        if not self.game.opponent and not self.game.completed:
            self.game.opponent = user
            self.game.save()
            return super(GameView, self).dispatch(request, *args, **kwargs)
        else:
            messages.add_message(request, messages.ERROR, 'Sorry, the selected game is not available.')
            return redirect('/lobby/')
项目:liberator    作者:libscie    | 项目源码 | 文件源码
def logout(self):
        """
        Removes the authenticated user's cookies and session object.

        Causes the authenticated user to be logged out.
        """
        from django.contrib.auth import get_user, logout

        request = HttpRequest()
        engine = import_module(settings.SESSION_ENGINE)
        if self.session:
            request.session = self.session
            request.user = get_user(request)
        else:
            request.session = engine.SessionStore()
        logout(request)
        self.cookies = SimpleCookie()
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
def logout(self):
        """
        Removes the authenticated user's cookies and session object.

        Causes the authenticated user to be logged out.
        """
        from django.contrib.auth import get_user, logout

        request = HttpRequest()
        engine = import_module(settings.SESSION_ENGINE)
        if self.session:
            request.session = self.session
            request.user = get_user(request)
        else:
            request.session = engine.SessionStore()
        logout(request)
        self.cookies = SimpleCookie()
项目:wger-lycan-clan    作者:andela    | 项目源码 | 文件源码
def get_user(request):
    if not hasattr(request, '_cached_user'):

        create_user = check_current_request(request)
        user = auth.get_user(request)

        # Set the flag in the session
        if not request.session.get('has_demo_data'):
            request.session['has_demo_data'] = False

        # Django didn't find a user, so create one now
        if settings.WGER_SETTINGS['ALLOW_GUEST_USERS'] and \
                request.method == 'GET' and \
                create_user and not user.is_authenticated():

            logger.debug('creating a new guest user now')
            user = create_temporary_user()
            django_login(request, user)

        request._cached_user = user
    return request._cached_user
项目:SciAuth    作者:hms-dbmi    | 项目源码 | 文件源码
def test_logout_view(self):

        # Logout.
        response = self.client.get(reverse(logout_view))

        # Check.
        self.assertRedirects(response, status_code=302,
                             target_status_code=404,
                             expected_url=settings.AUTH0_LOGOUT_URL,
                             msg_prefix='Logout did not redirect user to ' + settings.AUTH0_LOGOUT_URL)

        # See if the user is still logged in.
        user = get_user(self.client)
        self.assertFalse(user.is_authenticated())

        # Ensure user was logged out and session was cleared.
        self.assertEquals(len(self.client.session.items()), 0)
项目:finem_imperii    作者:jardiacaj    | 项目源码 | 文件源码
def setUp(self):
        self.client.post(
            reverse('account:login'),
            {'username': 'alice', 'password': 'test'},
        )
        user = auth.get_user(self.client)
        self.assertEqual(User.objects.get(id=1), user)
        self.client.get(
            reverse('character:activate', kwargs={'char_id': 6}),
            follow=True
        )

        self.not_my_unit = WorldUnit.objects.get(id=1)
        self.my_unit = WorldUnit.objects.get(id=2)
        initialize_unit(self.my_unit)
        initialize_unit(self.not_my_unit)
项目:finem_imperii    作者:jardiacaj    | 项目源码 | 文件源码
def setUp(self):
        self.client.post(
            reverse('account:login'),
            {'username': 'alice', 'password': 'test'},
        )
        user = auth.get_user(self.client)
        self.assertEqual(User.objects.get(id=1), user)

        self.active_character = Character.objects.get(id=6)

        self.client.get(
            reverse(
                'character:activate',
                kwargs={'char_id': self.active_character.id}
            ),
            follow=True
        )

        self.not_my_unit = WorldUnit.objects.get(id=1)
        self.my_unit = WorldUnit.objects.get(id=2)
        initialize_unit(self.my_unit)
        initialize_unit(self.not_my_unit)
项目:django-next-train    作者:bitpixdigital    | 项目源码 | 文件源码
def logout(self):
        """
        Removes the authenticated user's cookies and session object.

        Causes the authenticated user to be logged out.
        """
        from django.contrib.auth import get_user, logout

        request = HttpRequest()
        engine = import_module(settings.SESSION_ENGINE)
        if self.session:
            request.session = self.session
            request.user = get_user(request)
        else:
            request.session = engine.SessionStore()
        logout(request)
        self.cookies = SimpleCookie()
项目:django-wechat-api    作者:crazy-canux    | 项目源码 | 文件源码
def logout(self):
        """
        Removes the authenticated user's cookies and session object.

        Causes the authenticated user to be logged out.
        """
        from django.contrib.auth import get_user, logout

        request = HttpRequest()
        engine = import_module(settings.SESSION_ENGINE)
        if self.session:
            request.session = self.session
            request.user = get_user(request)
        else:
            request.session = engine.SessionStore()
        logout(request)
        self.cookies = SimpleCookie()
项目:dsa-sign-in-sheets    作者:PhillyDSA    | 项目源码 | 文件源码
def form_valid(self, form):
        resp = super().form_valid(form)
        self.object.event_admin = get_user(self.request)
        self.object.save()
        return resp
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def get_user(request):
    if not hasattr(request, '_cached_user'):
        request._cached_user = auth.get_user(request)
    return request._cached_user
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def process_request(self, request):
        assert hasattr(request, 'session'), (
            "The Django authentication middleware requires session middleware "
            "to be installed. Edit your MIDDLEWARE_CLASSES setting to insert "
            "'django.contrib.sessions.middleware.SessionMiddleware' before "
            "'django.contrib.auth.middleware.AuthenticationMiddleware'."
        )
        request.user = SimpleLazyObject(lambda: get_user(request))
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def get_user(request):
    if not hasattr(request, '_cached_user'):
        request._cached_user = auth.get_user(request)
    return request._cached_user
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def process_request(self, request):
        assert hasattr(request, 'session'), (
            "The Django authentication middleware requires session middleware "
            "to be installed. Edit your MIDDLEWARE%s setting to insert "
            "'django.contrib.sessions.middleware.SessionMiddleware' before "
            "'django.contrib.auth.middleware.AuthenticationMiddleware'."
        ) % ("_CLASSES" if settings.MIDDLEWARE is None else "")
        request.user = SimpleLazyObject(lambda: get_user(request))
项目:zing    作者:evernote    | 项目源码 | 文件源码
def get_user(request):
    if not hasattr(request, '_cached_user'):
        user = auth.get_user(request)
        request._cached_user = (user if user.is_authenticated else
                                auth.get_user_model().objects.get_nobody_user())
    return request._cached_user
项目:zing    作者:evernote    | 项目源码 | 文件源码
def process_request(self, request):
        assert hasattr(request, 'session'), (
            "The Django authentication middleware requires session middleware "
            "to be installed. Edit your MIDDLEWARE setting to insert "
            "'django.contrib.sessions.middleware.SessionMiddleware' before "
            "'django.contrib.auth.middleware.AuthenticationMiddleware'."
        )
        request.user = SimpleLazyObject(lambda: get_user(request))
项目:chatApp    作者:sherinann    | 项目源码 | 文件源码
def Message(request):
    if request.method=="POST":
        receiver=request.POST['receiver']
        message=request.POST['message']
        if User.objects.filter(username=receiver).exists():
            print("in")
            new=UserMessageInfo(sender=auth.get_user(request).username,receiver=receiver,message=message)
            new.save()
            return HttpResponseRedirect('/chat')
        else:
              return HttpResponseRedirect('/chat/messages')
    return render(request, 'chat/messages/message.html', {})
项目:chatApp    作者:sherinann    | 项目源码 | 文件源码
def Chats(request):              
    if request.method=="GET":
        chat_names = []
        username=auth.get_user(request).username
        info=UserMessageInfo.objects.filter(receiver=username).values_list('sender',flat=True)
        for i in info:
            if i not in chat_names:
                chat_names.append(i)
        info2=UserMessageInfo.objects.filter(sender=username).values_list('receiver',flat=True)
        for i in info2:
            if i not in chat_names:
                chat_names.append(i)
        print(chat_names)
        return render(request, 'chat/messages/chats.html', {'people':chat_names})
    return render(request, 'chat/messages/chats.html', {})
项目:valhalla    作者:LCOGT    | 项目源码 | 文件源码
def test_no_such_user(self):
        self.client.post(
            reverse('auth_login'),
            {'username': 'imnotreal', 'password': 'wrongpass'},
        )
        user = auth.get_user(self.client)
        self.assertFalse(user.is_authenticated)
项目:valhalla    作者:LCOGT    | 项目源码 | 文件源码
def test_login_fails(self):
        self.client.post(
            reverse('auth_login'),
            {'username': 'doge', 'password': 'wrongpass'},
        )
        user = auth.get_user(self.client)
        self.assertFalse(user.is_authenticated)
项目:valhalla    作者:LCOGT    | 项目源码 | 文件源码
def test_login(self):
        self.client.post(
            reverse('auth_login'),
            {'username': 'doge', 'password': 'sopassword'},
        )
        user = auth.get_user(self.client)
        self.assertTrue(user.is_authenticated)
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
def get_user(request):
    if not hasattr(request, '_cached_user'):
        request._cached_user = auth.get_user(request)
    return request._cached_user
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
def process_request(self, request):
        assert hasattr(request, 'session'), (
            "The Django authentication middleware requires session middleware "
            "to be installed. Edit your MIDDLEWARE%s setting to insert "
            "'django.contrib.sessions.middleware.SessionMiddleware' before "
            "'django.contrib.auth.middleware.AuthenticationMiddleware'."
        ) % ("_CLASSES" if settings.MIDDLEWARE is None else "")
        request.user = SimpleLazyObject(lambda: get_user(request))
项目:SPBU-DBMS-Project    作者:Betekhtin    | 项目源码 | 文件源码
def index(request):
    username = auth.get_user(request).username
    if (username):
        return render_to_response('index.html')
    else:
        return redirect("/login")
项目:SPBU-DBMS-Project    作者:Betekhtin    | 项目源码 | 文件源码
def about(request):
    username = auth.get_user(request).username
    if (username):
        return render_to_response('about.html')
    else:
        return redirect("/login")
项目:SPBU-DBMS-Project    作者:Betekhtin    | 项目源码 | 文件源码
def historyQuery(request):
    username = auth.get_user(request).username
    if (username):
        args = {}
        if request.POST:
            country=request.POST.get('country', '')
            city=request.POST.get('city', '')
            date_from=request.POST.get('date_from','')

            date_to=request.POST.get('date_to','')
            date_to = date_to + ' 23:00:00'
            d_temperature= list(temperature.objects.filter(date__gte=date_from, date__lte=date_to,city_id__exact=city).order_by('date').values())
            d_pressure =list(pressure.objects.filter(date__gte=date_from, date__lte=date_to, city_id__exact=city).order_by('date').values())
            d_weather = list(weather.objects.filter(date__gte=date_from, date__lte=date_to, city_id__exact=city).order_by('date').values())
            d_clouds = list(clouds.objects.filter(date__gte=date_from, date__lte=date_to, city_id__exact=city).order_by('date').values())
            d_other_weather_data = list(other_weather_data.objects.filter(date__gte=date_from, date__lte=date_to, city_id__exact=city).order_by('date').values())
            d_wind = list(wind.objects.filter(date__gte=date_from, date__lte=date_to, city_id__exact=city).order_by('date').values())
            # for i in listone:
            #     print(i['date'])
            # for i,j in zip(listone,listtwo):
            #      i.update(j)
            for a,b,c,d,e,f in zip(d_temperature, d_pressure,d_weather,d_clouds,d_other_weather_data,d_wind):
             a.update(b)
             a.update(c)
             a.update(d)
             a.update(e)
             a.update(f)

            args['data'] = d_temperature
            dom=parseString(xmlify(d_temperature, custom_root='weather',attr_type=False)).toprettyxml();
            dom=re.sub('\n+', '', dom)
            args['xml']= format_html(dom)

            return render_to_response("q_history.html", args)
        return redirect('/history')
    else:
        return redirect("/login")
项目:attendance-django    作者:wilcus    | 项目源码 | 文件源码
def register(request, course_id):
    course = Course.objects.get(pk=course_id)
    student_list_form = RegisterStudentListForm(course_id=course_id, professor=get_user(request))
    if request.method == 'POST':
        student_list_form = RegisterStudentListForm(course_id=course_id, professor=get_user(request), data=request.POST)
        if student_list_form.is_valid():
            student_list_form.save()
            messages.info(request, SUCCESS_MESSAGE)
        return render(request, 'register.html', {'course': course, 'form': student_list_form})
    return render(request, 'register.html', {'course': course, 'form': student_list_form})
项目:attendance-django    作者:wilcus    | 项目源码 | 文件源码
def registered(request, course_id, date):
    course = Course.objects.get(pk=course_id)
    students = Student.objects.filter(
        attendance__course__id=course_id,
        attendance__course__professors__in=[get_user(request)],
        attendance__date=date
    )
    date_ = timezone.datetime.strptime(date, "%Y-%m-%d").date()
    return render(request, 'registered.html', {'students': students, 'course': course, 'date_': date_})
项目:attendance-django    作者:wilcus    | 项目源码 | 文件源码
def registered_dates(request, course_id):
    course = Course.objects.get(pk=course_id)
    attendance_dates = Attendance.objects.filter(course_id=course_id, course__professors__in=[get_user(request)]).only('date').distinct().order_by('date')
    return render(request, 'registered_dates.html', {'attendance_dates': attendance_dates, 'course': course})
项目:attendance-django    作者:wilcus    | 项目源码 | 文件源码
def courses(request):
    courses = Course.objects.filter(professors__in=[get_user(request)])
    return render(request, 'courses.html', {'courses': courses})
项目:django    作者:alexsukhrin    | 项目源码 | 文件源码
def get_user(request):
    if not hasattr(request, '_cached_user'):
        request._cached_user = auth.get_user(request)
    return request._cached_user
项目:django    作者:alexsukhrin    | 项目源码 | 文件源码
def process_request(self, request):
        assert hasattr(request, 'session'), (
            "The Django authentication middleware requires session middleware "
            "to be installed. Edit your MIDDLEWARE%s setting to insert "
            "'django.contrib.sessions.middleware.SessionMiddleware' before "
            "'django.contrib.auth.middleware.AuthenticationMiddleware'."
        ) % ("_CLASSES" if settings.MIDDLEWARE is None else "")
        request.user = SimpleLazyObject(lambda: get_user(request))
项目:wagtail_room_booking    作者:Tamriel    | 项目源码 | 文件源码
def login_user(self):
        user = self.created_user
        if settings.ACCOUNT_USE_AUTH_AUTHENTICATE:
            # call auth.authenticate to ensure we set the correct backend for
            # future look ups using auth.get_user().
            user = auth.authenticate(**self.user_credentials())
        else:
            # set auth backend to ModelBackend, but this may not be used by
            # everyone. this code path is deprecated and will be removed in
            # favor of using auth.authenticate above.
            user.backend = "django.contrib.auth.backends.ModelBackend"
        auth.login(self.request, user)
        self.request.session.set_expiry(0)
项目:wagtail_room_booking    作者:Tamriel    | 项目源码 | 文件源码
def get(self, request, **kwargs):
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        ctx = self.get_context_data(form=form)
        if not self.check_token(self.get_user(), self.kwargs["token"]):
            return self.token_fail()
        return self.render_to_response(ctx)
项目:wagtail_room_booking    作者:Tamriel    | 项目源码 | 文件源码
def change_password(self, form):
        user = self.get_user()
        user.set_password(form.cleaned_data["password"])
        user.save()
项目:wagtail_room_booking    作者:Tamriel    | 项目源码 | 文件源码
def after_change_password(self):
        user = self.get_user()
        signals.password_changed.send(sender=PasswordResetTokenView, user=user)
        if settings.ACCOUNT_NOTIFY_ON_PASSWORD_CHANGE:
            self.send_email(user)
        if self.messages.get("password_changed"):
            messages.add_message(
                    self.request,
                    self.messages["password_changed"]["level"],
                    self.messages["password_changed"]["text"]
            )
项目:wagtail_room_booking    作者:Tamriel    | 项目源码 | 文件源码
def get_user(self):
        try:
            uid_int = base36_to_int(self.kwargs["uidb36"])
        except ValueError:
            raise Http404()
        return get_object_or_404(get_user_model(), id=uid_int)
项目:prestashop-sync    作者:dragoon    | 项目源码 | 文件源码
def __get__(self, request, obj_type=None):
        if not hasattr(request, '_cached_user'):
            request._cached_user = get_user(request)
            if request._cached_user.is_anonymous():
                try:
                    assert request.session.session_key
                    request._cached_user = Profile.objects.get(session__session_key=request.session.session_key)
                except (Profile.DoesNotExist, AssertionError):
                    request._cached_user = add_guest_data(request.session)
                    # We need to manually set flag to store session because we didn't modify it
                    # and we didn't "authenticated" our guest user
                    request.session.modified = True
        return request._cached_user
项目:intake    作者:codeforamerica    | 项目源码 | 文件源码
def assertLoggedInAs(self, user):
        client_user = auth.get_user(self.client)
        self.assertEqual(client_user, user)
        assert client_user.is_authenticated()
项目:kolibri    作者:learningequality    | 项目源码 | 文件源码
def list(self, request):
        logged_in_user = get_user(request)
        if type(logged_in_user) is AnonymousUser:
            return Response(Facility.objects.all().values_list('id', flat=True))
        else:
            return Response([logged_in_user.facility_id])
项目:kolibri    作者:learningequality    | 项目源码 | 文件源码
def _get_user(request):

    if not hasattr(request, '_cached_user'):
        user = get_user(request)
        if user.is_anonymous():
            user = KolibriAnonymousUser()
        request._cached_user = user

    return request._cached_user
项目:Gypsy    作者:benticarlos    | 项目源码 | 文件源码
def get_user(request):
    if not hasattr(request, '_cached_user'):
        request._cached_user = auth.get_user(request)
    return request._cached_user
项目:Gypsy    作者:benticarlos    | 项目源码 | 文件源码
def process_request(self, request):
        assert hasattr(request, 'session'), (
            "The Django authentication middleware requires session middleware "
            "to be installed. Edit your MIDDLEWARE%s setting to insert "
            "'django.contrib.sessions.middleware.SessionMiddleware' before "
            "'django.contrib.auth.middleware.AuthenticationMiddleware'."
        ) % ("_CLASSES" if settings.MIDDLEWARE is None else "")
        request.user = SimpleLazyObject(lambda: get_user(request))