Python django.views.generic.TemplateView.as_view() Examples

The following are 30 code examples for showing how to use django.views.generic.TemplateView.as_view(). 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.views.generic.TemplateView , or try the search function .

Example 1
Project: zulip   Author: zulip   File: auth.py    License: Apache License 2.0 6 votes vote down vote up
def config_error_view(request: HttpRequest, error_category_name: str) -> HttpResponse:
    contexts = {
        'apple': {'social_backend_name': 'apple', 'has_markdown_file': True},
        'google': {'social_backend_name': 'google', 'has_markdown_file': True},
        'github': {'social_backend_name': 'github', 'has_markdown_file': True},
        'gitlab': {'social_backend_name': 'gitlab', 'has_markdown_file': True},
        'ldap': {'error_name': 'ldap_error_realm_is_none'},
        'dev': {'error_name': 'dev_not_supported_error'},
        'saml': {'social_backend_name': 'saml'},
        'smtp': {'error_name': 'smtp_error'},
        'backend_disabled': {'error_name': 'remoteuser_error_backend_disabled'},
        'remote_user_header_missing': {'error_name': 'remoteuser_error_remote_user_header_missing'},
    }

    return TemplateView.as_view(template_name='zerver/config_error.html',
                                extra_context=contexts[error_category_name])(request) 
Example 2
Project: djongo   Author: nesdis   File: test_base.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_invalid_keyword_argument(self):
        """
        View arguments must be predefined on the class and can't
        be named like a HTTP method.
        """
        msg = (
            "You tried to pass in the %s method name as a keyword argument "
            "to SimpleView(). Don't do that."
        )
        # Check each of the allowed method names
        for method in SimpleView.http_method_names:
            with self.assertRaisesMessage(TypeError, msg % method):
                SimpleView.as_view(**{method: 'value'})

        # Check the case view argument is ok if predefined on the class...
        CustomizableView.as_view(parameter="value")
        # ...but raises errors otherwise.
        msg = (
            "CustomizableView() received an invalid keyword 'foobar'. "
            "as_view only accepts arguments that are already attributes of "
            "the class."
        )
        with self.assertRaisesMessage(TypeError, msg):
            CustomizableView.as_view(foobar="value") 
Example 3
Project: zulip   Author: zulip   File: auth.py    License: Apache License 2.0 5 votes vote down vote up
def start_two_factor_auth(request: HttpRequest,
                          extra_context: ExtraContext=None,
                          **kwargs: Any) -> HttpResponse:
    two_fa_form_field = 'two_factor_login_view-current_step'
    if two_fa_form_field not in request.POST:
        # Here we inject the 2FA step in the request context if it's missing to
        # force the user to go to the first step of 2FA authentication process.
        # This seems a bit hackish but simplifies things from testing point of
        # view. I don't think this can result in anything bad because all the
        # authentication logic runs after the auth step.
        #
        # If we don't do this, we will have to modify a lot of auth tests to
        # insert this variable in the request.
        request.POST = request.POST.copy()
        request.POST.update({two_fa_form_field: 'auth'})

    """
    This is how Django implements as_view(), so extra_context will be passed
    to the __init__ method of TwoFactorLoginView.

    def as_view(cls, **initkwargs):
        def view(request, *args, **kwargs):
            self = cls(**initkwargs)
            ...

        return view
    """
    two_fa_view = TwoFactorLoginView.as_view(extra_context=extra_context,
                                             **kwargs)
    return two_fa_view(request, **kwargs) 
Example 4
Project: zulip   Author: zulip   File: auth.py    License: Apache License 2.0 5 votes vote down vote up
def password_reset(request: HttpRequest) -> HttpResponse:
    if not Realm.objects.filter(string_id=get_subdomain(request)).exists():
        # If trying to get to password reset on a subdomain that
        # doesn't exist, just go to find_account.
        redirect_url = reverse('zerver.views.registration.find_account')
        return HttpResponseRedirect(redirect_url)

    view_func = DjangoPasswordResetView.as_view(template_name='zerver/reset.html',
                                                form_class=ZulipPasswordResetForm,
                                                success_url='/accounts/password/reset/done/')
    return view_func(request) 
Example 5
Project: djangoql   Author: ivelum   File: admin.py    License: MIT License 5 votes vote down vote up
def get_urls(self):
        custom_urls = []
        if self.djangoql_completion:
            custom_urls += [
                url(
                    r'^introspect/$',
                    self.admin_site.admin_view(self.introspect),
                    name='%s_%s_djangoql_introspect' % (
                        self.model._meta.app_label,
                        self.model._meta.model_name,
                    ),
                ),
                url(
                    r'^suggestions/$',
                    self.admin_site.admin_view(self.suggestions),
                    name='%s_%s_djangoql_suggestions' % (
                        self.model._meta.app_label,
                        self.model._meta.model_name,
                    ),
                ),
                url(
                    r'^djangoql-syntax/$',
                    self.admin_site.admin_view(TemplateView.as_view(
                        template_name=self.djangoql_syntax_help_template,
                    )),
                    name='djangoql_syntax_help',
                ),
            ]
        return custom_urls + super(DjangoQLSearchMixin, self).get_urls() 
Example 6
Project: djangoql   Author: ivelum   File: admin.py    License: MIT License 5 votes vote down vote up
def suggestions(self, request):
        view = SuggestionsAPIView.as_view(
            schema=self.djangoql_schema(self.model),
        )
        return view(request) 
Example 7
Project: cjworkbench   Author: CJWorkbench   File: urls.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def redirect(url: str):
    return RedirectView.as_view(url=url) 
Example 8
Project: builder   Author: Polychart   File: utils.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def template(templateName):
  """
  Simple shortcut for indicating in a Django routing file that a template
  should be rendered.
  """
  return TemplateView.as_view(template_name=templateName) 
Example 9
Project: builder   Author: Polychart   File: utils.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def permanentRedirect(targetUrl):
  """
  Simple shortcut for indicating a 301 redirect in a Django routing file.
  """
  return RedirectView.as_view(url=targetUrl, permanent=True) 
Example 10
Project: builder   Author: Polychart   File: utils.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def temporaryRedirect(targetUrl):
  """
  Simple shortcut for indicating a 302 redirect in a Django routing file.
  """
  return RedirectView.as_view(url=targetUrl, permanent=False) 
Example 11
Project: builder   Author: Polychart   File: utils.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def template(templateName):
  """
  Simple shortcut for indicating in a Django routing file that a template
  should be rendered.
  """
  return TemplateView.as_view(template_name=templateName) 
Example 12
Project: builder   Author: Polychart   File: utils.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def permanentRedirect(targetUrl):
  """
  Simple shortcut for indicating a 301 redirect in a Django routing file.
  """
  return RedirectView.as_view(url=targetUrl, permanent=True) 
Example 13
Project: djongo   Author: nesdis   File: test_base.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_no_init_kwargs(self):
        """
        A view can't be accidentally instantiated before deployment
        """
        with self.assertRaises(AttributeError):
            SimpleView(key='value').as_view() 
Example 14
Project: djongo   Author: nesdis   File: test_base.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_no_init_args(self):
        """
        A view can't be accidentally instantiated before deployment
        """
        with self.assertRaises(TypeError):
            SimpleView.as_view('value') 
Example 15
Project: djongo   Author: nesdis   File: test_base.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_pathological_http_method(self):
        """
        The edge case of a http request that spoofs an existing method name is caught.
        """
        self.assertEqual(SimpleView.as_view()(
            self.rf.get('/', REQUEST_METHOD='DISPATCH')
        ).status_code, 405) 
Example 16
Project: djongo   Author: nesdis   File: test_base.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_only(self):
        """
        Test a view which only allows GET doesn't allow other methods.
        """
        self._assert_simple(SimpleView.as_view()(self.rf.get('/')))
        self.assertEqual(SimpleView.as_view()(self.rf.post('/')).status_code, 405)
        self.assertEqual(SimpleView.as_view()(
            self.rf.get('/', REQUEST_METHOD='FAKE')
        ).status_code, 405) 
Example 17
Project: djongo   Author: nesdis   File: test_base.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_and_head(self):
        """
        Test a view which supplies a GET method also responds correctly to HEAD.
        """
        self._assert_simple(SimpleView.as_view()(self.rf.get('/')))
        response = SimpleView.as_view()(self.rf.head('/'))
        self.assertEqual(response.status_code, 200) 
Example 18
Project: djongo   Author: nesdis   File: test_base.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_and_post(self):
        """
        Test a view which only allows both GET and POST.
        """
        self._assert_simple(SimplePostView.as_view()(self.rf.get('/')))
        self._assert_simple(SimplePostView.as_view()(self.rf.post('/')))
        self.assertEqual(SimplePostView.as_view()(
            self.rf.get('/', REQUEST_METHOD='FAKE')
        ).status_code, 405) 
Example 19
Project: djongo   Author: nesdis   File: test_base.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_invalid_keyword_argument(self):
        """
        View arguments must be predefined on the class and can't
        be named like a HTTP method.
        """
        # Check each of the allowed method names
        for method in SimpleView.http_method_names:
            with self.assertRaises(TypeError):
                SimpleView.as_view(**{method: 'value'})

        # Check the case view argument is ok if predefined on the class...
        CustomizableView.as_view(parameter="value")
        # ...but raises errors otherwise.
        with self.assertRaises(TypeError):
            CustomizableView.as_view(foobar="value") 
Example 20
Project: djongo   Author: nesdis   File: test_base.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_calling_more_than_once(self):
        """
        Test a view can only be called once.
        """
        request = self.rf.get('/')
        view = InstanceView.as_view()
        self.assertNotEqual(view(request), view(request)) 
Example 21
Project: djongo   Author: nesdis   File: test_base.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_class_attributes(self):
        """
        The callable returned from as_view() has proper
        docstring, name and module.
        """
        self.assertEqual(SimpleView.__doc__, SimpleView.as_view().__doc__)
        self.assertEqual(SimpleView.__name__, SimpleView.as_view().__name__)
        self.assertEqual(SimpleView.__module__, SimpleView.as_view().__module__) 
Example 22
Project: djongo   Author: nesdis   File: test_base.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_dispatch_decoration(self):
        """
        Attributes set by decorators on the dispatch method
        are also present on the closure.
        """
        self.assertTrue(DecoratedDispatchView.as_view().is_decorated) 
Example 23
Project: djongo   Author: nesdis   File: test_base.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_options_for_get_view(self):
        """
        A view implementing GET allows GET and HEAD.
        """
        request = self.rf.options('/')
        view = SimpleView.as_view()
        response = view(request)
        self._assert_allows(response, 'GET', 'HEAD') 
Example 24
Project: djongo   Author: nesdis   File: test_base.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_options_for_get_and_post_view(self):
        """
        A view implementing GET and POST allows GET, HEAD, and POST.
        """
        request = self.rf.options('/')
        view = SimplePostView.as_view()
        response = view(request)
        self._assert_allows(response, 'GET', 'HEAD', 'POST') 
Example 25
Project: djongo   Author: nesdis   File: test_base.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_options_for_post_view(self):
        """
        A view implementing POST allows POST.
        """
        request = self.rf.options('/')
        view = PostOnlyView.as_view()
        response = view(request)
        self._assert_allows(response, 'POST') 
Example 26
Project: djongo   Author: nesdis   File: test_base.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_args_kwargs_request_on_self(self):
        """
        Test a view only has args, kwargs & request once `as_view`
        has been called.
        """
        bare_view = InstanceView()
        view = InstanceView.as_view()(self.rf.get('/'))
        for attribute in ('args', 'kwargs', 'request'):
            self.assertNotIn(attribute, dir(bare_view))
            self.assertIn(attribute, dir(view)) 
Example 27
Project: djongo   Author: nesdis   File: test_base.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_direct_instantiation(self):
        """
        It should be possible to use the view by directly instantiating it
        without going through .as_view() (#21564).
        """
        view = PostOnlyView()
        response = view.dispatch(self.rf.head('/'))
        self.assertEqual(response.status_code, 405) 
Example 28
Project: djongo   Author: nesdis   File: test_base.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_head(self):
        """
        Test a TemplateView responds correctly to HEAD
        """
        response = AboutTemplateView.as_view()(self.rf.head('/about/'))
        self.assertEqual(response.status_code, 200) 
Example 29
Project: djongo   Author: nesdis   File: test_base.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_template_attribute(self):
        """
        Test a view that renders a template on GET with the template name as
        an attribute on the class.
        """
        self._assert_about(AboutTemplateAttributeView.as_view()(self.rf.get('/about/'))) 
Example 30
Project: djongo   Author: nesdis   File: test_base.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_generic_template(self):
        """
        Test a completely generic view that renders a template on GET
        with the template name as an argument at instantiation.
        """
        self._assert_about(TemplateView.as_view(template_name='generic_views/about.html')(self.rf.get('/about/')))