Python django.shortcuts.resolve_url() Examples

The following are 30 code examples for showing how to use django.shortcuts.resolve_url(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.shortcuts , or try the search function .

Example 1
Project: django-ajax-contacts   Author: cuducos   File: views.py    License: The Unlicense 7 votes vote down vote up
def contact_detail(request, pk):
    if request.method == 'POST':
        data = (request.POST.get(key) for key in ('name', 'fone', 'email'))
        contact = Contact.objects.get(pk=pk)
        contact.name, contact.fone, contact.email = data
        contact.save()
    else:
        contact = get_object_or_404(Contact, pk=pk)

    response = dict(
        name=contact.name,
        avatar=contact.avatar(),
        email=contact.email,
        phone=contact.fone,
        url=resolve_url('contact-details', pk=contact.pk)
    )
    return JsonResponse(response) 
Example 2
Project: zulip   Author: zulip   File: decorator.py    License: Apache License 2.0 7 votes vote down vote up
def user_passes_test(test_func: Callable[[HttpResponse], bool], login_url: Optional[str]=None,
                     redirect_field_name: str=REDIRECT_FIELD_NAME) -> Callable[[ViewFuncT], ViewFuncT]:
    """
    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: ViewFuncT) -> ViewFuncT:
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request: HttpRequest, *args: object, **kwargs: object) -> HttpResponse:
            if test_func(request):
                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 = urllib.parse.urlparse(resolved_login_url)[:2]
            current_scheme, current_netloc = urllib.parse.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()
            return redirect_to_login(
                path, resolved_login_url, redirect_field_name)
        return cast(ViewFuncT, _wrapped_view)  # https://github.com/python/mypy/issues/1927
    return decorator 
Example 3
Project: GTDWeb   Author: lanbing510   File: views.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 
Example 4
Project: lmgtdfy   Author: opendata   File: views.py    License: MIT License 6 votes vote down vote up
def form_valid(self, form):
        data = form.cleaned_data
        domain = data['domain_base']
        domain_is_whitelisted = check_valid_tld(domain)
        if not domain_is_whitelisted:
            messages.info(
                self.request,
                "Sorry, but to limit the cost of running this service, we have not enabled searching this domain name (%s)." % domain
            )
            return HttpResponseRedirect(resolve_url('home'))

        search_done = search_bing(domain)
        if not search_done:
            messages.info(
                self.request,
                "This domain has already been requested today! Here is what we've gathered."
            )
        else:
            messages.info(
                self.request,
                "Gathering results now. They will be displayed shortly."
            )
        return HttpResponseRedirect(
            resolve_url('domain_result', domain)
        ) 
Example 5
Project: django-cas-ng   Author: django-cas-ng   File: utils.py    License: MIT License 6 votes vote down vote up
def get_redirect_url(request):
    """Redirects to referring page, or CAS_REDIRECT_URL if no referrer is
    set.
    """

    next_ = request.GET.get(REDIRECT_FIELD_NAME)
    if not next_:
        redirect_url = resolve_url(django_settings.CAS_REDIRECT_URL)
        if django_settings.CAS_IGNORE_REFERER:
            next_ = redirect_url
        else:
            next_ = request.META.get('HTTP_REFERER', redirect_url)
        prefix = urllib_parse.urlunparse(
            (get_protocol(request), request.get_host(), '', '', '', ''),
        )
        if next_.startswith(prefix):
            next_ = next_[len(prefix):]
    return next_ 
Example 6
Project: bioforum   Author: reBiocoder   File: views.py    License: MIT License 6 votes vote down vote up
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 
Example 7
Project: bioforum   Author: reBiocoder   File: views.py    License: MIT License 6 votes vote down vote up
def redirect_to_login(next, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Redirect 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 
Example 8
Project: bioforum   Author: reBiocoder   File: views.py    License: MIT License 6 votes vote down vote up
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 
Example 9
Project: django-sudo   Author: mattrobenolt   File: views.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def dispatch(self, request):
        redirect_to = request.GET.get(REDIRECT_FIELD_NAME, REDIRECT_URL)

        # Make sure we're not redirecting to other sites
        if not is_safe_url(url=redirect_to, host=request.get_host()):
            redirect_to = resolve_url(REDIRECT_URL)

        if request.is_sudo():
            return HttpResponseRedirect(redirect_to)

        if request.method == "GET":
            request.session[REDIRECT_TO_FIELD_NAME] = redirect_to

        context = {
            "form": self.form_class(request.user, request.POST or None),
            "request": request,
            REDIRECT_FIELD_NAME: redirect_to,
        }
        if self.handle_sudo(request, redirect_to, context):
            return self.grant_sudo_privileges(request, redirect_to)
        if self.extra_context is not None:
            context.update(self.extra_context)
        return TemplateResponse(request, self.template_name, context) 
Example 10
Project: django-sudo   Author: mattrobenolt   File: views.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def redirect_to_sudo(next_url, sudo_url=None):
    """
    Redirects the user to the login page, passing the given 'next' page
    """
    if sudo_url is None:
        sudo_url = URL

    try:
        # django 1.10 and greater can't resolve the string 'sudo.views.sudo' to a URL
        # https://docs.djangoproject.com/en/1.10/releases/1.10/#removed-features-1-10
        sudo_url = import_string(sudo_url)
    except (ImportError, ImproperlyConfigured):
        pass  # wasn't a dotted path

    sudo_url_parts = list(urlparse(resolve_url(sudo_url)))

    querystring = QueryDict(sudo_url_parts[4], mutable=True)
    querystring[REDIRECT_FIELD_NAME] = next_url
    sudo_url_parts[4] = querystring.urlencode(safe="/")

    return HttpResponseRedirect(urlunparse(sudo_url_parts)) 
Example 11
Project: zulip   Author: zulip   File: decorator.py    License: Apache License 2.0 6 votes vote down vote up
def redirect_to_login(next: str, login_url: Optional[str]=None,
                      redirect_field_name: str=REDIRECT_FIELD_NAME) -> HttpResponseRedirect:
    """
    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(urllib.parse.urlparse(resolved_url))
    if redirect_field_name:
        querystring = QueryDict(login_url_parts[4], mutable=True)
        querystring[redirect_field_name] = next
        # Don't add ?next=/, to keep our URLs clean
        if next != '/':
            login_url_parts[4] = querystring.urlencode(safe='/')

    return HttpResponseRedirect(urllib.parse.urlunparse(login_url_parts))

# From Django 1.8 
Example 12
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: views.py    License: MIT License 6 votes vote down vote up
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 
Example 13
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: views.py    License: MIT License 6 votes vote down vote up
def redirect_to_login(next, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Redirect 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))


# 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 
Example 14
Project: GetTogether   Author: GetTogetherComm   File: decorators.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def setup_wanted(view_func, setup_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Decorator for views that checks that the user has completed the setup
    process, redirecting to settings.SETUP_URL if required
    """

    @wraps(view_func)
    def wrap(request, *args, **kwargs):
        if (
            not request.user.is_authenticated
            or request.user.account.has_completed_setup
        ):
            return view_func(request, *args, **kwargs)
        else:
            resolved_setup_url = resolve_url(setup_url or settings.SETUP_URL)
            path = request.get_full_path()
            return redirect_to_login(path, resolved_setup_url, redirect_field_name)

    return wrap 
Example 15
Project: GetTogether   Author: GetTogetherComm   File: decorators.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def check_setup(request):
    """
    Checks if a user has completed setup
    """
    if not request.user.is_authenticated or request.user.account.has_completed_setup:
        return {"account_needs_setup": False, "current_user_account": None}
    elif request.user.account.has_completed_setup:
        return {
            "account_needs_setup": False,
            "current_user_account": request.user.account,
        }
    else:
        resolved_setup_url = resolve_url(settings.SETUP_URL)
        return {
            "account_needs_setup": True,
            "account_setup_url": resolved_setup_url,
            "current_user_account": request.user.account,
        } 
Example 16
Project: GetTogether   Author: GetTogetherComm   File: speakers.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_resume_adding_talk(self):
        user = User.objects.create(
            username="testuser", password="12345", is_active=True
        )

        c = Client()
        response = c.force_login(user)

        response = c.get(resolve_url("add-talk"))
        assert response.status_code == 302
        assert response.url == resolve_url("add-speaker")

        response = c.get(resolve_url("add-speaker"))
        assert response.status_code == 200
        response = c.post(
            resolve_url("add-speaker"), {"title": "test", "bio": "testing"}
        )
        assert response.status_code == 302
        assert response.url == resolve_url("add-talk") 
Example 17
Project: openhgsenti   Author: drexly   File: views.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 18
Project: hoover-search   Author: liquidinvestigations   File: middleware.py    License: MIT License 6 votes vote down vote up
def process_request(self, request):
        WHITELIST = [
            r'^/accounts/',
            r'^/invitation/',
            r'^/static/',
            r'^/_ping$',
            r'^/_is_staff$',
        ]
        for pattern in WHITELIST:
            if re.match(pattern, request.path):
                return

        user = request.user
        if user.is_verified():
            return

        resolved_login_url = resolve_url(settings.LOGIN_URL)
        return redirect_to_login(request.path, resolved_login_url, 'next') 
Example 19
Project: python2017   Author: bpgc-cte   File: views.py    License: MIT License 6 votes vote down vote up
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 
Example 20
Project: python2017   Author: bpgc-cte   File: views.py    License: MIT License 6 votes vote down vote up
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 
Example 21
Project: python2017   Author: bpgc-cte   File: views.py    License: MIT License 6 votes vote down vote up
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 
Example 22
Project: pets   Author: jllorencetti   File: test_list_pets_view.py    License: MIT License 6 votes vote down vote up
def test_content(self):
        """Should return the most important data, like name, description and city"""
        result = self.resp.content.decode()
        pet_profile = resolve_url("meupet:detail", self.pet.slug)
        user_profile = resolve_url("users:user_profile", self.pet.owner.id)

        contents = (
            "Araras",
            "Doralice",
            "Gato",
            "Dorinha",
            "Female",
            self.pet_status.description,
            "Small",
            pet_profile,
            user_profile,
            "https://fb.com/4",
        )

        for expected in contents:
            with self.subTest():
                self.assertIn(expected, result) 
Example 23
Project: django-ajax-contacts   Author: cuducos   File: views.py    License: The Unlicense 5 votes vote down vote up
def _contact_summary(contact):
    return dict(
        name=contact.name,
        avatar=contact.avatar(),
        url=resolve_url('contact-details', pk=contact.pk)
    ) 
Example 24
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def question_reorder(request: HttpRequest, course_slug: str, activity_slug: str, question_id: str) -> HttpResponse:
    quiz = get_object_or_404(Quiz, activity__slug=activity_slug, activity__offering__slug=course_slug)
    question1 = get_object_or_404(Question, quiz=quiz, id=question_id)

    direction = request.GET.get('direction', '')
    if direction not in ['up', 'down']:
        raise Http404()

    #if quiz.completed():
    #    return ForbiddenResponse(request, 'Quiz is completed. You cannot modify questions after the end of the quiz time')

    try:
        if direction == 'up':
            # find question before this one
            prev_order = Question.objects.filter(quiz=quiz, order__lt=question1.order).aggregate(Max('order'))['order__max']
            question2 = Question.objects.get(quiz=quiz, order=prev_order)
        else:
            # find question after this one
            next_order = Question.objects.filter(quiz=quiz, order__gt=question1.order).aggregate(Min('order'))['order__min']
            question2 = Question.objects.get(quiz=quiz, order=next_order)

    except Question.DoesNotExist:
        # moving up past the start, or down past the end: ignore
        pass

    else:
        o1 = question1.order
        o2 = question2.order
        with transaction.atomic():
            question2.order = o1
            question2.save()
            question1.order = o2
            question1.save()
            if quiz.activity.quiz_marking():
                # configured for quiz-based marking: update that so the order matches
                quiz.configure_marking(delete_others=False)
                messages.add_message(request, messages.INFO, 'Reordered marking rubric to match quiz questions.')

    return HttpResponseRedirect(resolve_url('offering:quiz:index', course_slug=course_slug, activity_slug=activity_slug)
                                + '#q-' + str(question1.id)) 
Example 25
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_absolute_url(self):
        return resolve_url('offering:quiz:index', course_slug=self.activity.offering.slug,
                           activity_slug=self.activity.slug) 
Example 26
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_absolute_url(self):
        return resolve_url('offering:quiz:index', course_slug=self.quiz.activity.offering.slug,
                           activity_slug=self.quiz.activity.slug) + '#' + self.ident() 
Example 27
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_absolute_url(self):
        return resolve_url('offering:quiz:view_submission', course_slug=self.question.quiz.activity.offering.slug,
                           activity_slug=self.question.quiz.activity.slug,
                           userid=self.student.person.userid_or_emplid()) + '#' + self.question.ident() 
Example 28
Project: coursys   Author: sfu-fas   File: file.py    License: GNU General Public License v3.0 5 votes vote down vote up
def secret_url(self, questionanswer):
        return settings.BASE_ABS_URL + resolve_url(
            'offering:quiz:submitted_file',
            course_slug=self.question.quiz.activity.offering.slug,
            activity_slug=self.question.quiz.activity.slug,
            userid=questionanswer.student.person.userid_or_emplid(),
            answer_id=questionanswer.id,
            secret=questionanswer.answer['data'].get('secret', '?')
        ) 
Example 29
Project: GTDWeb   Author: lanbing510   File: decorators.py    License: GNU General Public License v2.0 5 votes vote down vote up
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 
Example 30
Project: GTDWeb   Author: lanbing510   File: views.py    License: GNU General Public License v2.0 5 votes vote down vote up
def login(request, template_name='registration/login.html',
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm,
          current_app=None, 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)

    if current_app is not None:
        request.current_app = current_app

    return TemplateResponse(request, template_name, context)