Python django.shortcuts 模块,resolve_url() 实例源码

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

项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
def password_reset_complete(request,
                            template_name='registration/password_reset_complete.html',
                            extra_context=None):
    warnings.warn("The password_reset_complete() view is superseded by the "
                  "class-based PasswordResetCompleteView().",
                  RemovedInDjango21Warning, stacklevel=2)
    context = {
        'login_url': resolve_url(settings.LOGIN_URL),
        'title': _('Password reset complete'),
    }
    if extra_context is not None:
        context.update(extra_context)

    return TemplateResponse(request, template_name, context)


# Class-based password reset views
# - PasswordResetView sends the mail
# - PasswordResetDoneView shows a success message for the above
# - PasswordResetConfirmView checks the link the user clicked and
#   prompts for a new password
# - PasswordResetCompleteView shows a success message for the above
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def redirect_to_login(next, login_url=None,
                      redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Redirects the user to the login page, passing the given 'next' page
    """
    resolved_url = resolve_url(login_url or settings.LOGIN_URL)

    login_url_parts = list(urlparse(resolved_url))
    if redirect_field_name:
        querystring = QueryDict(login_url_parts[4], mutable=True)
        querystring[redirect_field_name] = next
        login_url_parts[4] = querystring.urlencode(safe='/')

    return HttpResponseRedirect(urlunparse(login_url_parts))


# 4 views for password reset:
# - password_reset sends the mail
# - password_reset_done shows a success message for the above
# - password_reset_confirm checks the link the user clicked and
#   prompts for a new password
# - password_reset_complete shows a success message for the above
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def redirect_to_login(next, login_url=None,
                      redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Redirects the user to the login page, passing the given 'next' page
    """
    resolved_url = resolve_url(login_url or settings.LOGIN_URL)

    login_url_parts = list(urlparse(resolved_url))
    if redirect_field_name:
        querystring = QueryDict(login_url_parts[4], mutable=True)
        querystring[redirect_field_name] = next
        login_url_parts[4] = querystring.urlencode(safe='/')

    return HttpResponseRedirect(urlunparse(login_url_parts))


# 4 views for password reset:
# - password_reset sends the mail
# - password_reset_done shows a success message for the above
# - password_reset_confirm checks the link the user clicked and
#   prompts for a new password
# - password_reset_complete shows a success message for the above
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
def get_next_page(self):
        if self.next_page is not None:
            next_page = resolve_url(self.next_page)
        elif settings.LOGOUT_REDIRECT_URL:
            next_page = resolve_url(settings.LOGOUT_REDIRECT_URL)
        else:
            next_page = self.next_page

        if (self.redirect_field_name in self.request.POST or
                self.redirect_field_name in self.request.GET):
            next_page = self.request.POST.get(
                self.redirect_field_name,
                self.request.GET.get(self.redirect_field_name)
            )
            url_is_safe = is_safe_url(
                url=next_page,
                allowed_hosts=self.get_success_url_allowed_hosts(),
                require_https=self.request.is_secure(),
            )
            # Security check -- Ensure the user-originating redirection URL is
            # safe.
            if not url_is_safe:
                next_page = self.request.path
        return next_page
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
def redirect_to_login(next, login_url=None,
                      redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Redirects the user to the login page, passing the given 'next' page
    """
    resolved_url = resolve_url(login_url or settings.LOGIN_URL)

    login_url_parts = list(urlparse(resolved_url))
    if redirect_field_name:
        querystring = QueryDict(login_url_parts[4], mutable=True)
        querystring[redirect_field_name] = next
        login_url_parts[4] = querystring.urlencode(safe='/')

    return HttpResponseRedirect(urlunparse(login_url_parts))


# 4 views for password reset:
# - password_reset sends the mail
# - password_reset_done shows a success message for the above
# - password_reset_confirm checks the link the user clicked and
#   prompts for a new password
# - password_reset_complete shows a success message for the above
项目:valentina    作者:valentinavc    | 项目源码 | 文件源码
def test_contents_new_messages(self):
        """Once user joins a chat, she should see new messages only"""

        # test user says hi and others reply
        Message.objects.create(user=self.user, chat=self.chat, content='Hi')
        Message.objects.create(user=User.objects.get(pk=1),
                               chat=self.chat, content='Hi')
        Message.objects.create(user=User.objects.get(pk=2),
                               chat=self.chat, content='Hi')
        resp = self.client.get(resolve_url('app:chat', self.chat.hash_id),
                               HTTP_X_REQUESTED_WITH='XMLHttpRequest')

        json_resp = resp.json()
        with self.subTest():
            self.assertEqual(json_resp['chat']['key'], self.chat.hash_id)
            self.assertEqual(json_resp['chat']['alias'], 'Geek')
            self.assertEqual(json_resp['chat']['user'], 'Olivia')
            self.assertEqual(3, len(json_resp['messages']))
项目:PublicAPI    作者:InternetSemLimites    | 项目源码 | 文件源码
def provider_new(request):
    if request.method != 'POST':
        return HttpResponseNotAllowed(['POST'])

    form = ProviderForm(request.POST)
    if not form.is_valid():
        return JsonResponse({'errors': form.errors})

    provider = form.save()
    _send_mail('+1 InternetSemLimites',
               settings.DEFAULT_FROM_EMAIL,
               list(_get_admin_emails()),
               'core/provider_email.txt',
               dict(provider=provider))

    return HttpResponseRedirect(resolve_url('api:provider', provider.pk))
项目:django    作者:alexsukhrin    | 项目源码 | 文件源码
def get_next_page(self):
        if self.next_page is not None:
            next_page = resolve_url(self.next_page)
        elif settings.LOGOUT_REDIRECT_URL:
            next_page = resolve_url(settings.LOGOUT_REDIRECT_URL)
        else:
            next_page = self.next_page

        if (self.redirect_field_name in self.request.POST or
                self.redirect_field_name in self.request.GET):
            next_page = self.request.POST.get(
                self.redirect_field_name,
                self.request.GET.get(self.redirect_field_name)
            )
            url_is_safe = is_safe_url(
                url=next_page,
                allowed_hosts=self.get_success_url_allowed_hosts(),
                require_https=self.request.is_secure(),
            )
            # Security check -- Ensure the user-originating redirection URL is
            # safe.
            if not url_is_safe:
                next_page = self.request.path
        return next_page
项目:django    作者:alexsukhrin    | 项目源码 | 文件源码
def redirect_to_login(next, login_url=None,
                      redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Redirects the user to the login page, passing the given 'next' page
    """
    resolved_url = resolve_url(login_url or settings.LOGIN_URL)

    login_url_parts = list(urlparse(resolved_url))
    if redirect_field_name:
        querystring = QueryDict(login_url_parts[4], mutable=True)
        querystring[redirect_field_name] = next
        login_url_parts[4] = querystring.urlencode(safe='/')

    return HttpResponseRedirect(urlunparse(login_url_parts))


# 4 views for password reset:
# - password_reset sends the mail
# - password_reset_done shows a success message for the above
# - password_reset_confirm checks the link the user clicked and
#   prompts for a new password
# - password_reset_complete shows a success message for the above
项目:django    作者:alexsukhrin    | 项目源码 | 文件源码
def password_reset_complete(request,
                            template_name='registration/password_reset_complete.html',
                            extra_context=None):
    warnings.warn("The password_reset_complete() view is superseded by the "
                  "class-based PasswordResetCompleteView().",
                  RemovedInDjango21Warning, stacklevel=2)
    context = {
        'login_url': resolve_url(settings.LOGIN_URL),
        'title': _('Password reset complete'),
    }
    if extra_context is not None:
        context.update(extra_context)

    return TemplateResponse(request, template_name, context)


# Class-based password reset views
# - PasswordResetView sends the mail
# - PasswordResetDoneView shows a success message for the above
# - PasswordResetConfirmView checks the link the user clicked and
#   prompts for a new password
# - PasswordResetCompleteView shows a success message for the above
项目:wttd    作者:renzon    | 项目源码 | 文件源码
def talk_list_get(client):
    activities = [
        Talk(title='Título da Palestra', start='10:00',
             description='Descrição da palestra.'),
        Talk(title='Título da Palestra', start='13:00',
             description='Descrição da palestra.'),
        Course(title='Título do Curso', start='9:00',
               description='Descrição do curso.', slots=20)
    ]
    speaker = Speaker.objects.create(
        name='Henrique Bastos',
        slug='henrique-bastos',
        website='//henriquebastos.net',
    )

    for a in activities:
        a.save()
        a.speakers.add(speaker)
    return client.get(resolve_url('talk_list'))
项目:jarbas    作者:datasciencebr    | 项目源码 | 文件源码
def setUp(self):
        self.reimbursement = get_reimbursement(
            year=2017,
            applicant_id=1,
            document_id=20,
            receipt_url='http://www.camara.gov.br/cota-parlamentar/documentos/publ/1/2017/20.pdf'
        )
        self.reimbursement_no_receipt = get_reimbursement(receipt_url=None)
        self.url = resolve_url(
            'chamber_of_deputies:reimbursement-receipt',
            document_id=self.reimbursement.document_id
        )
        self.url_no_receipt = resolve_url(
            'chamber_of_deputies:reimbursement-receipt',
            document_id=self.reimbursement_no_receipt.document_id
        )
项目:eventex    作者:paulopinda    | 项目源码 | 文件源码
def setUp(self):
        t1 = Talk.objects.create(title='Título da Palestra', start='10:00',
                            description='Descrição da palestra.')
        t2 = Talk.objects.create(title='Título da Palestra', start='13:00',
                            description='Descrição da palestra.')
        c1 = Course.objects.create(title='Título do Curso', start='09:00',
                                      description='Descrição do curso.', slots=20)

        self.speaker = Speaker.objects.create(name='Paulo Roberto', slug='paulo-roberto',
                                         website='http://paulosilva.info')

        t1.speakers.add(self.speaker)
        t2.speakers.add(self.speaker)
        c1.speakers.add(self.speaker)

        self.resp = self.client.get(r('talk_list'))
项目:tumanov_castleoaks    作者:Roamdev    | 项目源码 | 文件源码
def get(self, request, *args, **kwargs):
        # Seo
        seo = Seo()
        seo.title = _('Password reset')
        seo.save(request)

        if request.user.is_authenticated():
            # ????? ?????? ??????, ???? ????????????
            form = SetPasswordForm(request.user)
            return self.render_to_response({
                'form': form,
                'target': resolve_url('users:reset_self'),
            })
        else:
            return password_reset(request,
                template_name='users/reset.html',
                password_reset_form=PasswordResetForm,
            )
项目:tumanov_castleoaks    作者:Roamdev    | 项目源码 | 文件源码
def get(self, request, uidb64=None, token=None):
        if request.user.is_authenticated():
            return redirect(get_redirect_url(request))

        # Seo
        seo = Seo()
        seo.title = _('Password reset')
        seo.save(request)

        try:
            uid = urlsafe_base64_decode(uidb64)
            user = UserModel._default_manager.get(pk=uid)
        except (TypeError, ValueError, OverflowError, ObjectDoesNotExist):
            user = None

        if user is None or not default_token_generator.check_token(user, token):
            return redirect(resolve_url(settings.RESET_PASSWORD_REDIRECT_URL))

        return password_reset_confirm(request,
            uidb64=uidb64,
            token=token,
            template_name='users/reset_confirm.html',
            set_password_form=SetPasswordForm,
            post_reset_redirect='users:reset_complete',
        )
项目:tumanov_castleoaks    作者:Roamdev    | 项目源码 | 文件源码
def get(self, request, *args, **kwargs):
        # Seo
        seo = Seo()
        seo.title = _('Password reset')
        seo.save(request)

        if request.user.is_authenticated():
            return redirect(get_redirect_url(request))
        else:
            email = request.session.pop('reset_email', '')
            if not email:
                return redirect(resolve_url(settings.RESET_PASSWORD_REDIRECT_URL))

            return self.render_to_response({
                'redirect': resolve_url(settings.RESET_PASSWORD_REDIRECT_URL),
            })
项目:tumanov_castleoaks    作者:Roamdev    | 项目源码 | 文件源码
def get(self, request, *args, username=None, **kwargs):
        if not username and not request.user.is_authenticated():
            return redirect(settings.LOGIN_URL)

        request.js_storage.update(
            avatar_upload=resolve_url('users:avatar_upload'),
            avatar_crop=resolve_url('users:avatar_crop'),
            avatar_delete=resolve_url('users:avatar_delete'),
        )

        if username:
            user = get_object_or_404(UserModel, username=username)
        elif not request.user.is_authenticated():
            raise Http404
        else:
            user = request.user

        # Seo
        seo = Seo()
        seo.title = _('Profile of «%(username)s»') % {'username': user.username}
        seo.save(request)

        return self.render_to_response({
            'profile_user': user,
        })
项目:tumanov_castleoaks    作者:Roamdev    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        try:
            obj = self.instance.get_edited_object()
        except ObjectDoesNotExist:
            self.fields['object_link'].widget = forms.HiddenInput()
            self.fields['object_link'].help_text = '--//--'
        else:
            self.initial['object_link'] = self.instance.get_admin_url()
            self.fields['object_link'].widget.text = str(obj)

        if self.instance.user:
            admin_user_model = settings.AUTH_USER_MODEL.lower().replace('.', '_')
            self.initial['user_link'] = resolve_url('admin:{}_change'.format(admin_user_model), self.instance.user.pk)
            self.fields['user_link'].widget.text = str(self.instance.user)
        else:
            self.fields['user_link'].widget = forms.HiddenInput()
            self.fields['user_link'].help_text = '--//--'
项目:tumanov_castleoaks    作者:Roamdev    | 项目源码 | 文件源码
def get(self, request, *args, **kwargs):
        code = request.GET.get('code', '')
        if not code:
            raise Http404

        config = SocialConfig.get_solo()
        redirect_uri = self.request.build_absolute_uri(resolve_url('admin_social_networks:instagram_token'))
        response = requests.post(
            'https://api.instagram.com/oauth/access_token',
            data={
                'grant_type': 'authorization_code',
                'client_id': config.instagram_client_id,
                'client_secret': config.instagram_client_secret,
                'redirect_uri': redirect_uri,
                'code': code,
            }
        )

        answer = response.json()
        if answer and 'access_token' in answer:
            SocialConfig.objects.update(instagram_access_token=answer['access_token'])
            add_message(request, SUCCESS, _('Instagram access_token updated successfully!'))
            return redirect('admin:social_networks_socialconfig_change')
        else:
            return HttpResponse(response.text)
项目:tumanov_castleoaks    作者:Roamdev    | 项目源码 | 文件源码
def get(self, request, *args, **kwargs):
        code = request.GET.get('code', '')
        if not code:
            raise Http404

        config = SocialConfig.get_solo()
        redirect_uri = self.request.build_absolute_uri(resolve_url('admin_social_networks:linkedin_token'))
        response = requests.post(
            'https://www.linkedin.com/oauth/v2/accessToken',
            data={
                'grant_type': 'authorization_code',
                'client_id': config.linkedin_client_id,
                'client_secret': config.linkedin_client_secret,
                'redirect_uri': redirect_uri,
                'code': code,
            }
        )

        answer = response.json()
        if answer and 'access_token' in answer:
            SocialConfig.objects.update(linkedin_access_token=answer['access_token'])
            add_message(request, SUCCESS, _('LinkedIn access_token updated successfully!'))
            return redirect('admin:social_networks_socialconfig_change')
        else:
            return HttpResponse(response.text)
项目:tumanov_castleoaks    作者:Roamdev    | 项目源码 | 文件源码
def get_referer_url(request):
    """
        ?????????? ????????????? ???? REFERER, ???? ?? ? ???????? ?????.
        ?????, ?????????? MULTILANGUAGE_FALLBACK_URL
    """
    referer = request.META.get('HTTP_REFERER')
    if not referer:
        return resolve_url(options.MULTILANGUAGE_FALLBACK_URL)

    site = get_current_site(request)
    url_parts = list(urlparse(referer))
    if url_parts[1] != site.domain:
        return resolve_url(options.MULTILANGUAGE_FALLBACK_URL)

    url_parts[0] = ''
    url_parts[1] = ''
    return urlunparse(url_parts)
项目:tumanov_castleoaks    作者:Roamdev    | 项目源码 | 文件源码
def __init__(self, title, url, attrs=None, item_id=''):
        super().__init__()
        self._parent = None
        self._item_id = item_id
        self._title = str(title)

        try:
            self._url = resolve_url(url)
        except NoReverseMatch:
            self._url = url

        if attrs is None:
            self._classes = ''
            self._attrs = ''
        else:
            self._classes = attrs.pop('class', '')
            self._attrs = flatatt(attrs)
项目:tumanov_castleoaks    作者:Roamdev    | 项目源码 | 文件源码
def away_links(request, html):
    """
        ???????? ??? ??????? ?????? ? html-???? ?? ?????? ????? ? ??????????
    """
    site = get_current_site(request)
    soup = Soup(html, 'html5lib')
    for tag in soup.findAll('a'):
        if tag.get('href'):
            parsed = parse.urlparse(tag['href'])
            if '' not in (parsed.scheme, parsed.netloc) \
                    and not parsed.query \
                    and not is_same_domain(parsed.netloc, site.domain):
                tag['target'] = '_blank'
                tag['href'] = resolve_url('away') + '?url=' + parsed.geturl()
                if tag.string:
                    tag.string = parse.unquote(tag.string)

    return soup.body.decode_contents()
项目:tumanov_castleoaks    作者:Roamdev    | 项目源码 | 文件源码
def away(request):
    referer = request.META.get('HTTP_REFERER')
    if not referer:
        return redirect(settings.LOGIN_REDIRECT_URL)

    # ??????????, ??? ? REFERER ???????? ???
    referer = urlparse(referer)
    if '' in (referer.scheme, referer.netloc):
        return redirect(settings.LOGIN_REDIRECT_URL)

    # ?????????, ??? ??????? ? ?????? ?????
    site = get_current_site(request)
    if not is_same_domain(referer.netloc, site.domain):
        return redirect(settings.LOGIN_REDIRECT_URL)

    url = request.GET.get('url') or resolve_url('index')
    return render(request, 'away/away.html', {
        'url': url
    })
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def login(request, template_name='registration/login.html',
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm,
          extra_context=None):
    """
    Displays the login form and handles the login action.
    """
    redirect_to = request.POST.get(redirect_field_name,
                                   request.GET.get(redirect_field_name, ''))

    if request.method == "POST":
        form = authentication_form(request, data=request.POST)
        if form.is_valid():

            # Ensure the user-originating redirection url is safe.
            if not is_safe_url(url=redirect_to, host=request.get_host()):
                redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)

            # Okay, security check complete. Log the user in.
            auth_login(request, form.get_user())

            return HttpResponseRedirect(redirect_to)
    else:
        form = authentication_form(request)

    current_site = get_current_site(request)

    context = {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
    }
    if extra_context is not None:
        context.update(extra_context)

    return TemplateResponse(request, template_name, context)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def logout(request, next_page=None,
           template_name='registration/logged_out.html',
           redirect_field_name=REDIRECT_FIELD_NAME,
           extra_context=None):
    """
    Logs out the user and displays 'You are logged out' message.
    """
    auth_logout(request)

    if next_page is not None:
        next_page = resolve_url(next_page)

    if (redirect_field_name in request.POST or
            redirect_field_name in request.GET):
        next_page = request.POST.get(redirect_field_name,
                                     request.GET.get(redirect_field_name))
        # Security check -- don't allow redirection to a different host.
        if not is_safe_url(url=next_page, host=request.get_host()):
            next_page = request.path

    if next_page:
        # Redirect to this page until the session has been cleared.
        return HttpResponseRedirect(next_page)

    current_site = get_current_site(request)
    context = {
        'site': current_site,
        'site_name': current_site.name,
        'title': _('Logged out')
    }
    if extra_context is not None:
        context.update(extra_context)

    return TemplateResponse(request, template_name, context)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def logout_then_login(request, login_url=None, extra_context=None):
    """
    Logs out the user if they are logged in. Then redirects to the log-in page.
    """
    if not login_url:
        login_url = settings.LOGIN_URL
    login_url = resolve_url(login_url)
    return logout(request, login_url, extra_context=extra_context)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def password_reset_complete(request,
                            template_name='registration/password_reset_complete.html',
                            extra_context=None):
    context = {
        'login_url': resolve_url(settings.LOGIN_URL),
        'title': _('Password reset complete'),
    }
    if extra_context is not None:
        context.update(extra_context)

    return TemplateResponse(request, template_name, context)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def password_change(request,
                    template_name='registration/password_change_form.html',
                    post_change_redirect=None,
                    password_change_form=PasswordChangeForm,
                    extra_context=None):
    if post_change_redirect is None:
        post_change_redirect = reverse('password_change_done')
    else:
        post_change_redirect = resolve_url(post_change_redirect)
    if request.method == "POST":
        form = password_change_form(user=request.user, data=request.POST)
        if form.is_valid():
            form.save()
            # Updating the password logs out all other sessions for the user
            # except the current one if
            # django.contrib.auth.middleware.SessionAuthenticationMiddleware
            # is enabled.
            update_session_auth_hash(request, form.user)
            return HttpResponseRedirect(post_change_redirect)
    else:
        form = password_change_form(user=request.user)
    context = {
        'form': form,
        'title': _('Password change'),
    }
    if extra_context is not None:
        context.update(extra_context)

    return TemplateResponse(request, template_name, context)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Decorator for views that checks that the user passes the given test,
    redirecting to the log-in page if necessary. The test should be a callable
    that takes the user object and returns True if the user passes.
    """

    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            if test_func(request.user):
                return view_func(request, *args, **kwargs)
            path = request.build_absolute_uri()
            resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
            # If the login url is the same scheme and net location then just
            # use the path as the "next" url.
            login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
            current_scheme, current_netloc = urlparse(path)[:2]
            if ((not login_scheme or login_scheme == current_scheme) and
                    (not login_netloc or login_netloc == current_netloc)):
                path = request.get_full_path()
            from django.contrib.auth.views import redirect_to_login
            return redirect_to_login(
                path, resolved_login_url, redirect_field_name)
        return _wrapped_view
    return decorator
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def _get_login_redirect_url(request, redirect_to):
    # Ensure the user-originating redirection URL is safe.
    if not is_safe_url(url=redirect_to, host=request.get_host()):
        return resolve_url(settings.LOGIN_REDIRECT_URL)
    return redirect_to
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def logout(request, next_page=None,
           template_name='registration/logged_out.html',
           redirect_field_name=REDIRECT_FIELD_NAME,
           extra_context=None):
    """
    Logs out the user and displays 'You are logged out' message.
    """
    auth_logout(request)

    if next_page is not None:
        next_page = resolve_url(next_page)
    elif settings.LOGOUT_REDIRECT_URL:
        next_page = resolve_url(settings.LOGOUT_REDIRECT_URL)

    if (redirect_field_name in request.POST or
            redirect_field_name in request.GET):
        next_page = request.POST.get(redirect_field_name,
                                     request.GET.get(redirect_field_name))
        # Security check -- don't allow redirection to a different host.
        if not is_safe_url(url=next_page, host=request.get_host()):
            next_page = request.path

    if next_page:
        # Redirect to this page until the session has been cleared.
        return HttpResponseRedirect(next_page)

    current_site = get_current_site(request)
    context = {
        'site': current_site,
        'site_name': current_site.name,
        'title': _('Logged out')
    }
    if extra_context is not None:
        context.update(extra_context)

    return TemplateResponse(request, template_name, context)
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def logout_then_login(request, login_url=None, extra_context=None):
    """
    Logs out the user if they are logged in. Then redirects to the log-in page.
    """
    if not login_url:
        login_url = settings.LOGIN_URL
    login_url = resolve_url(login_url)
    return logout(request, login_url, extra_context=extra_context)
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def password_reset(request,
                   template_name='registration/password_reset_form.html',
                   email_template_name='registration/password_reset_email.html',
                   subject_template_name='registration/password_reset_subject.txt',
                   password_reset_form=PasswordResetForm,
                   token_generator=default_token_generator,
                   post_reset_redirect=None,
                   from_email=None,
                   extra_context=None,
                   html_email_template_name=None,
                   extra_email_context=None):
    if post_reset_redirect is None:
        post_reset_redirect = reverse('password_reset_done')
    else:
        post_reset_redirect = resolve_url(post_reset_redirect)
    if request.method == "POST":
        form = password_reset_form(request.POST)
        if form.is_valid():
            opts = {
                'use_https': request.is_secure(),
                'token_generator': token_generator,
                'from_email': from_email,
                'email_template_name': email_template_name,
                'subject_template_name': subject_template_name,
                'request': request,
                'html_email_template_name': html_email_template_name,
                'extra_email_context': extra_email_context,
            }
            form.save(**opts)
            return HttpResponseRedirect(post_reset_redirect)
    else:
        form = password_reset_form()
    context = {
        'form': form,
        'title': _('Password reset'),
    }
    if extra_context is not None:
        context.update(extra_context)

    return TemplateResponse(request, template_name, context)
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def password_reset_complete(request,
                            template_name='registration/password_reset_complete.html',
                            extra_context=None):
    context = {
        'login_url': resolve_url(settings.LOGIN_URL),
        'title': _('Password reset complete'),
    }
    if extra_context is not None:
        context.update(extra_context)

    return TemplateResponse(request, template_name, context)
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def password_change(request,
                    template_name='registration/password_change_form.html',
                    post_change_redirect=None,
                    password_change_form=PasswordChangeForm,
                    extra_context=None):
    if post_change_redirect is None:
        post_change_redirect = reverse('password_change_done')
    else:
        post_change_redirect = resolve_url(post_change_redirect)
    if request.method == "POST":
        form = password_change_form(user=request.user, data=request.POST)
        if form.is_valid():
            form.save()
            # Updating the password logs out all other sessions for the user
            # except the current one.
            update_session_auth_hash(request, form.user)
            return HttpResponseRedirect(post_change_redirect)
    else:
        form = password_change_form(user=request.user)
    context = {
        'form': form,
        'title': _('Password change'),
    }
    if extra_context is not None:
        context.update(extra_context)

    return TemplateResponse(request, template_name, context)
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Decorator for views that checks that the user passes the given test,
    redirecting to the log-in page if necessary. The test should be a callable
    that takes the user object and returns True if the user passes.
    """

    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            if test_func(request.user):
                return view_func(request, *args, **kwargs)
            path = request.build_absolute_uri()
            resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
            # If the login url is the same scheme and net location then just
            # use the path as the "next" url.
            login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
            current_scheme, current_netloc = urlparse(path)[:2]
            if ((not login_scheme or login_scheme == current_scheme) and
                    (not login_netloc or login_netloc == current_netloc)):
                path = request.get_full_path()
            from django.contrib.auth.views import redirect_to_login
            return redirect_to_login(
                path, resolved_login_url, redirect_field_name)
        return _wrapped_view
    return decorator
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
def get_success_url(self):
        """Ensure the user-originating redirection URL is safe."""
        redirect_to = self.request.POST.get(
            self.redirect_field_name,
            self.request.GET.get(self.redirect_field_name, '')
        )
        url_is_safe = is_safe_url(
            url=redirect_to,
            allowed_hosts=self.get_success_url_allowed_hosts(),
            require_https=self.request.is_secure(),
        )
        if not url_is_safe:
            return resolve_url(settings.LOGIN_REDIRECT_URL)
        return redirect_to
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
def logout_then_login(request, login_url=None, extra_context=_sentinel):
    """
    Logs out the user if they are logged in. Then redirects to the log-in page.
    """
    if extra_context is not _sentinel:
        warnings.warn(
            "The unused `extra_context` parameter to `logout_then_login` "
            "is deprecated.", RemovedInDjango21Warning
        )

    if not login_url:
        login_url = settings.LOGIN_URL
    login_url = resolve_url(login_url)
    return LogoutView.as_view(next_page=login_url)(request)
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
def get_context_data(self, **kwargs):
        context = super(PasswordResetCompleteView, self).get_context_data(**kwargs)
        context['login_url'] = resolve_url(settings.LOGIN_URL)
        return context
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
def password_change(request,
                    template_name='registration/password_change_form.html',
                    post_change_redirect=None,
                    password_change_form=PasswordChangeForm,
                    extra_context=None):
    warnings.warn("The password_change() view is superseded by the "
                  "class-based PasswordChangeView().",
                  RemovedInDjango21Warning, stacklevel=2)
    if post_change_redirect is None:
        post_change_redirect = reverse('password_change_done')
    else:
        post_change_redirect = resolve_url(post_change_redirect)
    if request.method == "POST":
        form = password_change_form(user=request.user, data=request.POST)
        if form.is_valid():
            form.save()
            # Updating the password logs out all other sessions for the user
            # except the current one.
            update_session_auth_hash(request, form.user)
            return HttpResponseRedirect(post_change_redirect)
    else:
        form = password_change_form(user=request.user)
    context = {
        'form': form,
        'title': _('Password change'),
    }
    if extra_context is not None:
        context.update(extra_context)

    return TemplateResponse(request, template_name, context)
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Decorator for views that checks that the user passes the given test,
    redirecting to the log-in page if necessary. The test should be a callable
    that takes the user object and returns True if the user passes.
    """

    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            if test_func(request.user):
                return view_func(request, *args, **kwargs)
            path = request.build_absolute_uri()
            resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
            # If the login url is the same scheme and net location then just
            # use the path as the "next" url.
            login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
            current_scheme, current_netloc = urlparse(path)[:2]
            if ((not login_scheme or login_scheme == current_scheme) and
                    (not login_netloc or login_netloc == current_netloc)):
                path = request.get_full_path()
            from django.contrib.auth.views import redirect_to_login
            return redirect_to_login(
                path, resolved_login_url, redirect_field_name)
        return _wrapped_view
    return decorator
项目:valentina    作者:valentinavc    | 项目源码 | 文件源码
def logout(request):
    auth_logout(request)
    return redirect(resolve_url('home'))
项目:valentina    作者:valentinavc    | 项目源码 | 文件源码
def _should_abort_user(request, should_redirect):

    # authorize if user is staff
    if request.user.is_staff:
        return False

    # authorize if user is female and not blocked
    not_female = False
    blocked = False
    if hasattr(request.user, 'profile'):
        if request.user.profile.gender == Profile.FEMALE:
            if not request.user.profile.blocked:
                return False
            else:
                blocked = True
        else:
            not_female = True

    auth_logout(request)
    if should_redirect:
        if not_female:
            return redirect(resolve_url('female_only'))
        elif blocked:
            return redirect(resolve_url('blocked'))

    return HttpResponseForbidden()
项目:valentina    作者:valentinavc    | 项目源码 | 文件源码
def _affiliation_to_dict(affiliation):
    return dict(url=resolve_url('app:chat', affiliation.chat.hash_id),
                key=affiliation.hash_id,
                alias=affiliation.alias,
                active=affiliation.active,
                valentinas=affiliation.chat.affiliation_set.count())
项目:valentina    作者:valentinavc    | 项目源码 | 文件源码
def setUp(self):

        # handle user and chat database objects
        user_data = {'password': self.PASSWORD}
        self.user = User.objects.create_user(self.USERNAME, **user_data)
        self.chat = Chat.objects.first()
        profile_data = {'user': self.user, 'nickname': self.NICKNAME,
                        'gender': Profile.FEMALE}
        self.profile = Profile.objects.create(**profile_data)
        affiliation_data = {'chat': self.chat, 'user': self.user,
                            'alias': self.CHAT_ALIAS}
        self.affiliation = Affiliation.objects.create(**affiliation_data)
        self.message = Message.objects.first()

        # list all URLs, their allowed methods, and the required data
        self.cases = ({'url': resolve_url('app:chat', self.chat.hash_id),
                       'allowed_methods': ('get', 'post'),
                       'data': {'content': 'Hey', 'chat': self.chat.hash_id}},
                      {'url': resolve_url('app:profile'),
                       'allowed_methods': ('post'),
                       'data': {'nickname': 'Olivia'}},
                      {'url': resolve_url('app:affiliation'),
                       'allowed_methods': ('post'),
                       'data': {'alias': 'Guy', 'person': '4'}},
                      {'url': resolve_url('app:report'),
                       'allowed_methods': ('post'),
                       'data': {'pk': self.message.hash_id}})

        # set main vars for HTTP request tests
        self.ajax_header = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}
        self.methods = {'get': self.client.get,
                        'post': self.client.post,
                        'put': self.client.put,
                        'patch': self.client.patch,
                        'delete': self.client.delete}
项目:valentina    作者:valentinavc    | 项目源码 | 文件源码
def test_requests_without_login(self):
        """
        All methods should redirect to login page when user is not logged in
        """
        requests = self.get_all_requests()
        for url, method, allowed, resp, ajax in requests:
            with self.subTest():
                expected = '{}?next={}'.format(resolve_url('home'), url)
                self.assertRedirects(resp, expected)
项目:valentina    作者:valentinavc    | 项目源码 | 文件源码
def setUp(self):

        # create user with password and affiliate her to a chatroom
        self.user = User.objects.create_user('valentinavc', password='valentina')
        self.chat = Chat.objects.first()
        Profile.objects.create(user=self.user, gender=Profile.FEMALE, nickname='valanon')
        Affiliation.objects.create(chat=self.chat, user=self.user, alias='Geek')

        # login and POST
        self.login = self.client.login(username='valentinavc',
                                       password='valentina')
        data = {'content': 'Hello, world', 'chat': self.chat.pk}
        self.resp = self.client.post(resolve_url('app:chat', self.chat.hash_id),
                                     data, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
项目:valentina    作者:valentinavc    | 项目源码 | 文件源码
def setUp(self):
        User.objects.create_user('olivia', password='password')
        self.client.login(username='olivia', password='password')
        self.resp = self.client.get(resolve_url('app:logout'))