Python django.views.generic.View() Examples

The following are 30 code examples of django.views.generic.View(). 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 also want to check out all available functions/classes of the module django.views.generic , or try the search function .
Example #1
Source File: decorators.py    From sal with Apache License 2.0 6 votes vote down vote up
def class_access_required(cls):
    """Decorator for View subclasses to restrict by business unit.

    Class must declare a classmethod `get_business_unit` that returns
    the BusinessUnit object that applies to the query in question.

    Args:
        cls: Class to decorate.

    Returns:
        Decorated class.

    Raises:
        403 Pemission Denied if current user does not have access.
        404 if requested group doesn't exist.
    """
    def access_required(function):
        def decorator(*args, **kwargs):
            # The request object is the first arg to a view
            request = args[0]
            user = request.user
            business_unit = cls.get_business_unit(**kwargs)

            if has_access(user, business_unit):
                return function(*args, **kwargs)
            else:
                raise PermissionDenied()
        return decorator

    access_decorator = method_decorator(access_required)
    cls.dispatch = access_decorator(cls.dispatch)
    return cls 
Example #2
Source File: decorators.py    From sal with Apache License 2.0 6 votes vote down vote up
def get_business_unit_by(model, **kwargs):
    try:
        pk = [v for k, v in kwargs.items() if k.endswith('_id')].pop()
    except IndexError:
        raise ValueError('View lacks an ID parameter!')

    try:
        instance = get_object_or_404(model, pk=pk)
    except ValueError:
        # Sal allows machine serials instead of machine ID in URLs.
        # Handle that special case.
        if model is Machine:
            instance = get_object_or_404(model, serial=pk)

    if isinstance(instance, MachineGroup):
        return (instance, instance.business_unit)
    elif isinstance(instance, Machine):
        return (instance, instance.machine_group.business_unit)
    else:
        return (instance, instance) 
Example #3
Source File: test_base.py    From djongo with 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 #4
Source File: decorators.py    From sal with Apache License 2.0 6 votes vote down vote up
def required_level(*decorator_args):
    """View decorator to redirect users without acceptable userprofile..

    Wrapped function must have the request object as the first argument.

    Args:
        *args (server.model.UserProfile.LEVEL_CHOICES) Any number of
            user profile level choices that should be permitted access.
    """

    def decorator(function):

        @wraps(function)
        def wrapper(*args, **kwargs):
            if args[0].user.userprofile.level not in decorator_args:
                return redirect(reverse('home'))
            else:
                return function(*args, **kwargs)

        return wrapper

    return decorator 
Example #5
Source File: decorators.py    From DjangoUnleashed-1.8 with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def require_authenticated_permission(permission):

    def decorator(cls):
        if (not isinstance(cls, type)
                or not issubclass(cls, View)):
            raise ImproperlyConfigured(
                "require_authenticated_permission"
                " must be applied to subclasses "
                "of View class.")
        check_auth = (
            method_decorator(login_required))
        check_perm = (
            method_decorator(
                permission_required(
                    permission,
                    raise_exception=True)))

        cls.dispatch = (
            check_auth(check_perm(cls.dispatch)))
        return cls

    return decorator 
Example #6
Source File: pages.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def approve_moderation(request, revision_id):
    revision = get_object_or_404(PageRevision, id=revision_id)
    if not revision.page.permissions_for_user(request.user).can_publish():
        raise PermissionDenied

    if not revision.submitted_for_moderation:
        messages.error(request, _("The page '{0}' is not currently awaiting moderation.").format(revision.page.get_admin_display_title()))
        return redirect('wagtailadmin_home')

    if request.method == 'POST':
        revision.approve_moderation()

        message = _("Page '{0}' published.").format(revision.page.get_admin_display_title())
        buttons = []
        if revision.page.url is not None:
            buttons.append(messages.button(revision.page.url, _('View live'), new_window=True))
        buttons.append(messages.button(reverse('wagtailadmin_pages:edit', args=(revision.page.id,)), _('Edit')))
        messages.success(request, message, buttons=buttons)

        if not send_notification(revision.id, 'approved', request.user.pk):
            messages.error(request, _("Failed to send approval notifications"))

    return redirect('wagtailadmin_home') 
Example #7
Source File: auth.py    From volontulo with MIT License 6 votes vote down vote up
def activate(request, uuid):
    """View responsible for activating user account."""
    try:
        profile = UserProfile.objects.get(uuid=uuid)
        profile.user.is_active = True
        profile.user.save()
        messages.success(
            request,
            """Pomyślnie aktywowałeś użytkownika."""
        )
    except UserProfile.DoesNotExist:
        messages.error(
            request,
            """Brak użytkownika spełniającego wymagane kryteria."""
        )
    return redirect('homepage') 
Example #8
Source File: offers.py    From volontulo with MIT License 6 votes vote down vote up
def post(request, slug, id_):
        u"""View responsible for submitting volunteers awarding."""
        offer = get_object_or_404(Offer, id=id_)
        post_data = request.POST
        if post_data.get('csrfmiddlewaretoken'):
            del post_data['csrfmiddlewaretoken']
        if post_data.get('submit'):
            del post_data['submit']

        offer.votes = True
        offer.save()

        context = {
            'offer': offer,
        }
        return render(request, "offers/show_offer.html", context=context) 
Example #9
Source File: decorators.py    From DjangoUnleashed-1.8 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def class_login_required(cls):
    if (not isinstance(cls, type)
            or not issubclass(cls, View)):
        raise ImproperlyConfigured(
            "class_login_required"
            " must be applied to subclasses "
            "of View class.")
    decorator = method_decorator(login_required)
    cls.dispatch = decorator(cls.dispatch)
    return cls 
Example #10
Source File: decorators.py    From sal with Apache License 2.0 5 votes vote down vote up
def staff_required(function):
    """View decorator to redirect non staff users.

    Wrapped function must have the request object as the first argument.
    """
    @wraps(function)
    def wrapper(*args, **kwargs):
        if not args[0].user.is_staff:
            return redirect(reverse('home'))
        else:
            return function(*args, **kwargs)

    return wrapper 
Example #11
Source File: views.py    From djradicale with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, **kwargs):
        super(DjRadicaleView, self).__init__()
        super(View, self).__init__(**kwargs) 
Example #12
Source File: views.py    From djradicale with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, **kwargs):
        super(DjRadicaleView, self).__init__()
        super(View, self).__init__(**kwargs) 
Example #13
Source File: mixin.py    From ecommerce_website_development with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def as_view(cls, **initkwargs):
        # 调用View类中as_view
        view = super().as_view(**initkwargs)

        # 调用login_required装饰器函数
        return login_required(view) 
Example #14
Source File: test_views.py    From django-rules with MIT License 5 votes vote down vote up
def test_unknown_view_type(self):
        class TestView(AutoPermissionRequiredMixin, View):
            pass

        with self.assertRaises(ImproperlyConfigured):
            TestView.as_view()(self.req) 
Example #15
Source File: views.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def get_view_name(view_cls, suffix=None):
    """
    Given a view class, return a textual name to represent the view.
    This name is used in the browsable API, and in OPTIONS responses.
    This function is the default for the `VIEW_NAME_FUNCTION` setting.
    """
    name = view_cls.__name__
    name = formatting.remove_trailing_string(name, 'View')
    name = formatting.remove_trailing_string(name, 'ViewSet')
    name = formatting.camelcase_to_spaces(name)
    if suffix:
        name += ' ' + suffix

    return name 
Example #16
Source File: decorators.py    From sal with Apache License 2.0 5 votes vote down vote up
def class_ga_required(cls):
    """Class decorator for View subclasses to restrict to GA."""
    decorator = method_decorator(ga_required)
    cls.dispatch = decorator(cls.dispatch)
    return cls 
Example #17
Source File: views.py    From django-facebook-messenger-bot-tutorial with MIT License 5 votes vote down vote up
def dispatch(self, request, *args, **kwargs):
        return generic.View.dispatch(self, request, *args, **kwargs)

    # Post function to handle Facebook messages 
Example #18
Source File: test_base.py    From djongo with 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 #19
Source File: test_base.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_template_params(self):
        """
        A generic template view passes kwargs as context.
        """
        response = self.client.get('/template/simple/bar/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['foo'], 'bar')
        self.assertIsInstance(response.context['view'], View) 
Example #20
Source File: test_base.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_extra_template_params(self):
        """
        A template view can be customized to return extra context.
        """
        response = self.client.get('/template/custom/bar/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['foo'], 'bar')
        self.assertEqual(response.context['key'], 'value')
        self.assertIsInstance(response.context['view'], View) 
Example #21
Source File: test_base.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_not_calling_parent_setup_error(self):
        class TestView(View):
            def setup(self, request, *args, **kwargs):
                pass  # Not calling supre().setup()

        msg = (
            "TestView instance has no 'request' attribute. Did you override "
            "setup() and forget to call super()?"
        )
        with self.assertRaisesMessage(AttributeError, msg):
            TestView.as_view()(self.rf.get('/')) 
Example #22
Source File: test_base.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_extra_template_params(self):
        """
        A template view can be customized to return extra context.
        """
        response = self.client.get('/template/custom/bar/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['foo'], 'bar')
        self.assertEqual(response.context['key'], 'value')
        self.assertIsInstance(response.context['view'], View) 
Example #23
Source File: organizations.py    From volontulo with MIT License 5 votes vote down vote up
def organizations_list(request):
    u"""View responsible for listing all organizations.

    :param request: WSGIRequest instance
    """
    organizations = Organization.objects.all()
    return render(
        request,
        "organizations/list.html",
        {'organizations': organizations},
    ) 
Example #24
Source File: test_api.py    From normandy with Mozilla Public License 2.0 5 votes vote down vote up
def test_register_view_requires_name(self):
        router = MixedViewRouter()
        with pytest.raises(TypeError) as err:
            router.register_view("view", View, allow_cdn=True)
        assert "missing 1 required keyword-only argument: 'name'" in str(err.value) 
Example #25
Source File: test_api.py    From normandy with Mozilla Public License 2.0 5 votes vote down vote up
def test_get_urls_includes_non_viewset_views(self):
        router = MixedViewRouter()
        router.register_view("view", View, name="standalone-view")
        urls = router.get_urls()
        assert len(urls) == 1
        assert urls[0].name == "standalone-view" 
Example #26
Source File: views.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_success_url(self):
        return reverse('fieldsight:region-list', kwargs={'pk': self.object.project.id})


# class RegionDeactivateView(View):
#
#     def get(self, request, pk, *args, **kwargs):
#         region = Region.objects.get(pk=pk)
#         project_id = region.project.id
#         site=Site.objects.filter(region_id=self.kwargs.get('pk'))
#         site.update(region=None)
#         region.is_active = False
#         region.save()
#
#         return HttpResponseRedirect(reverse('fieldsight:project-dashboard', kwargs={'pk':region.project.id})) 
Example #27
Source File: permissions.py    From spacenews with MIT License 5 votes vote down vote up
def has_permission(self, request: Request, view: View) -> bool:
        if request.method in permissions.SAFE_METHODS:
            return True
        return request.user.is_authenticated 
Example #28
Source File: permissions.py    From spacenews with MIT License 5 votes vote down vote up
def has_object_permission(
        self, request: Request, view: View, obj: Any
    ) -> bool:
        if request.method in permissions.SAFE_METHODS:
            return True

        if not request.user.is_authenticated:
            return False

        return obj.author == request.user 
Example #29
Source File: permissions.py    From spacenews with MIT License 5 votes vote down vote up
def has_permission(self, request: Request, view: View) -> bool:
        if request.method in permissions.SAFE_METHODS:
            return True
        return request.user.is_authenticated 
Example #30
Source File: permissions.py    From spacenews with MIT License 5 votes vote down vote up
def has_object_permission(
        self, request: Request, view: View, obj: Any
    ) -> bool:

        if request.method in permissions.SAFE_METHODS:
            return True

        if not request.user.is_authenticated:
            return False

        return obj.author == request.user