Reusable, generic mixins for Django

Overview

django-braces

Mixins for Django's class-based views.

Latest Travis CI status PyPI version

Documentation

Read The Docs

Installation

Install from PyPI with pip: pip install django-braces

Building the Docs

  1. Install docs requirements: pip install -r requirements-docs.txt.
  2. cd docs.
  3. make html.
  4. Open _build/index.html in your browser.

Contributing

See our contribution guide

Add yourself to CONTRIBUTORS.txt if you want.

All development dependencies are available in requirements.txt file.

To run the test suite, please install tox and as many Python interpreters as you'd like to test against. Currently we test against 2.7, 3.6, 3.7, and 3.8. We recommend using asdf to install various Python versions.

Once tox and Python(s) are installed, you can execute the entire suite by running just the tox command.

Change Log

Changelog on Read The Docs

Supported Django Versions

Our policy is that django-braces officially supports, and is tested on, all versions that Django officially supports. You are free to use django-braces with any version of Django you wish (so long as it has class-based views) but no support will be promised.

Comments
  • Login required without exception, permission required with

    Login required without exception, permission required with

    I require the functionality to create a view that redirects to the login page if the user is not logged in, but raises an exception if they are but do not have the correct permissions. In vanilla Django, I'd do the following:

    @login_required
    @permission_required('my_permission', raise_exception=True)
    def my_view(request):
        pass
    

    Doing this using the LoginRequiredMixin and the PermissionRequiredMixin is impossible, as they both use the same raise_exception class-level variable.

    This would apply to the MultiplePermissionsRequiredMixin also.

    opened by benbacardi 15
  • PermissionRequiredMixin doesn't allow custom permissions/object permissions

    PermissionRequiredMixin doesn't allow custom permissions/object permissions

    The PermissionRequiredMixin does not allow for checking custom object permissions provided by libraries like django object permissions or django-guardian.

    I was thinking of updating it to be similar to https://github.com/lukaszb/django-guardian/blob/master/guardian/mixins.py#L52

    Except stripping out the parts where it does object specific actions or guardian specific things, and allow overriding to implement said functionality.

    opened by chancez 15
  • Potential mixin contributions - sortable-listview & spreadsheet-response

    Potential mixin contributions - sortable-listview & spreadsheet-response

    Hi lovely django-braces people, hope this is the right place for this, I wasn't sure how best to reach you otherwise. Am a huge fan of braces, use it a lot.

    I have two mixins which I'm wondering whether you might be interested in. If so, I'd be delighted to do the work to get them fit for braces, they already have some tests, but not python 3 etc..

    django-spreadsheetresponsemixin - https://github.com/birdsarah/django-spreadsheetresponsemixin Renders views that have a queryset e.g. a ListView, into an excel spreadsheet or a CSV. Takes headers from model or you can customize them. Can specify fields and order columns by doing so. Maybe you don't want to rely on additional libraries, so maybe just the CSV portion would be interesting.

    django-sortable-listview - https://github.com/aptivate/django-sortable-listview Like OrderableListMixin but takes things a bit further, for example, if you're already sorted in one direction it'll provide context data so that the next sort can be in the opposite direction. Obviously, would be happy to pull out specific features and add them to the existing OrderableListMixin.

    Thanks in advance for your thoughts.

    opened by birdsarah 14
  • redirect_unauthenticated_users will cause raise_exception to be ignored

    redirect_unauthenticated_users will cause raise_exception to be ignored

    When chaining LoginRequiredMixin and another AccessMixin, setting raise_exception = True and redirect_unauthenticated_users = True doesn't seem to do the right thing.

    opened by cornmander 12
  • Adding OwnerOrPermissionRequiredMixin

    Adding OwnerOrPermissionRequiredMixin

    I have made a mixin that checks if the user is regarded as owner for an object, if not it checks if the user has the given permission. Nice to have for Django's UpdateView or DeleteView. Tests and docs are updated :)

    opened by erlingbo 12
  • Added a cache mixin [builds on #159]

    Added a cache mixin [builds on #159]

    Picking up on work done by @omerzimp in #159. Addressing concerns in #159 and adding tests. Last modified times must now also be timezone-aware datetimes.

    Edit: Todos:

    • [x] Initial documentation
    • [x] Support for conditional retrieval (see the condition mixin)
    • [x] ~~Consider sha1'ing the response from get_etag(), and rename to get_etag_data()~~ No, a separate ETag class could provide better functionality, but that's probably out of scope for now.
    • [x] Add support for Cache-Control: private/public
    • [x] Finalise documentation
    opened by adamcharnock 10
  • Django 1.4 - braces tag 1.4.0 error

    Django 1.4 - braces tag 1.4.0 error

    The doc on github says that works but is not working.

    1.4.x will be the last version to officially support Django 1.4.x

    Django 1.4.1-final, 0

    ImportError at /admin/xxxxx
    cannot import name force_text
    
    opened by alexsilva 9
  • OwnerRequiredMixin

    OwnerRequiredMixin

    What about adding an OwnerRequiredMixin to work with the DetailView, UpdateView and DeleteView views.

    Something like ...

    class OwnerRequiredMixin(object):
    
        def dispatch(self, request, *args, **kwargs):
            self.object = self.get_object()
    
            if request.user != self.object.user:
                raise PermissionDenied
    
            return super(OwnerRequiredMixin, self).dispatch(request, *args, **kwargs)
    
    opened by epicserve 9
  • Customizable LoginRequiredMixin

    Customizable LoginRequiredMixin

    The LoginRequiredMixin was lacking the ability to customize login_url, redirect field, or redirect path per view because it was using a decorator. Since these things need to change based on instance, we are using the redirect_to_login view directly instead of the login_required decorator, and we are adding methods and properties which allow us to micro-manage the view instances.

    opened by foxbunny 9
  • TBD: access mixins: support for custom exceptions

    TBD: access mixins: support for custom exceptions

    I wanted to use a custom exception with SuperuserRequiredMixin (Http404) and added support for it.

    raise_exception can now be True, False, a custom exception or a callable (that should return a response).

    I have then factored the no-permission handling into a separate function, and moved redirect_unauthenticated_users to the base mixin.

    This does not include any documentation changes yet, because I wanted to gather feedback on it first.

    E.g., I am not sure if handle_no_permission should fall back to raising an exception for any non-HTTP-response (not isinstance(ret, (HttpResponse, StreamingHttpResponse))).

    opened by blueyed 8
  • Add PrepareMixin

    Add PrepareMixin

    I've added here a mixin we use intermittently when the normal flow of a class-based view becomes awkward. It allows you to place permission and/or existence checking earlier in the process in a more reusable way, especially useful when dealing with permissions of related objects. It also allows you to do more than just 404 if permissions are different which is hard to do from within a normal integration point (e.g. get_object). Hopefully my documentation makes sense!

    Personally I find this updated dispatch method a much cleaner way to do checking early in a view compared to messing around in the dispatch method, mainly as args, kwargs, request are all set already. Perhaps some of the other mixins here could be made cleaner using this, I've not looked too closely.

    I'm open to changes of terminology if you think the naming is unclear.

    opened by mjtamlyn 8
  • docs: Fix a few typos

    docs: Fix a few typos

    There are small typos in:

    • docs/other.rst
    • tests/test_access_mixins.py

    Fixes:

    • Should read respond rather than responsed.
    • Should read passing rather than passsing.

    Semi-automated pull request generated by https://github.com/timgates42/meticulous/blob/master/docs/NOTE.md

    opened by timgates42 1
  • Django 4 ajax

    Django 4 ajax

    need change:

    class AjaxResponseMixin(object): def dispatch(self, request, *args, **kwargs): request_method = request.method.lower()

        if request.is_ajax and request_method in self.http_method_names:
    

    here modify: if request.headers.get('x-requested-with') == 'XMLHttpRequest' and request_method in self.http_method_names:

    its work now

    opened by jonaqp 2
  • Cleaner approach to `HeaderMixin`

    Cleaner approach to `HeaderMixin`

    satisfying

    This PR introduces a backwards-compatible change to the HeaderMixin. Our existing method works but feels kind of heavy-handed. This approach is more in-line with Django's design, IMO, and doesn't feel as blunt.

    Unfortunately, it only works if render_to_response is ultimately called, so I had to leave in the old approach as well. Maybe we should split it up into a new mixin?

    opened by kennethlove 1
  • Look at refactoring tests

    Look at refactoring tests

    Our tests seem a little overly complicated. We should make sure they're as easy to write as possible.

    Maybe we should have a "how to write a test" guide

    opened by kennethlove 0
Releases(v1.15.0)
  • v1.15.0(Nov 5, 2021)

    • Updates and fixes from https://github.com/brack3t/django-braces/pull/265
    • Typo fixes from https://github.com/brack3t/django-braces/pull/269 and https://github.com/brack3t/django-braces/pull/262
    • Formatted project with black
    • Dropped explicit support for Python versions before 3.7 and non-LTS versions of Django
    Source code(tar.gz)
    Source code(zip)
  • v1.14.0(Dec 30, 2019)

  • v1.13.0(Dec 23, 2019)

  • v1.12.0(Dec 23, 2019)

  • v1.11.0(Dec 23, 2019)

  • v1.10.0(Dec 23, 2019)

  • 1.9.0(May 31, 2016)

    • [Feature] #203: Use Django’s supplied version of six to remove an external dependency.
    • [Bug] #161: Fixed redirect loop for users without proper groups for MultipleGroupRequiredMixin and GroupRequiredMixin.
    • [Bug] #181: Fixed redirect loops based on user permissions.
    • [Bug] #196: Refactor how users without permissions are handled.
    • [Bug] #208: Fixed errors from combining certain access mixins.
    • [Support]: Added note to docs about Python and Django versions used in tests.
    • [Support] #192: Added example for OrderableListView.
    • [Support] #201: Fixed typo in SuccessURLRedirectListMixin.
    • [Support] #202: Fixed typo in PermissionsRequiredMixin and MultiplePermissionsRequiredMixin.
    • [Support] #209: Fixed link to Django documentation for user_passes_test decorator.
    Source code(tar.gz)
    Source code(zip)
  • v1.8.0(Apr 17, 2015)

    • #145 Allow custom exceptions to be raised by all AccessMixins.
    • #171 New SSLRequiredMixin. Redirect http -> https.
    • #138 New RecentLoginRequiredMixin to require user sessions to have a given freshness.
    • #164 Use resolve_url to handle LOGIN_REDIRECT_URLs in settings.py that are just URL names.
    • #130 New attribute on JSONResponseMixin to allow setting a custom JSON encoder class.
    • #131 New attribute on LoginRequiredMixin so it's possible to redirect unauthenticated users while using AccessMixin-derived mixins instead of throwing an exception.
    Source code(tar.gz)
    Source code(zip)
  • v1.4.0(Mar 4, 2014)

    • Split views.py out into multiple files since it was approaching 1000 LoC.
    • SetHeadlineMixin now accepts headline with ugettext_lazy()-wrapped strings.
    • Fixed a bug where JSONResponseMixin would override the content_type of Django's TemplateView in Django 1.6.
    • Fixed bug in PermissionRequiredMixin where if PermissionRequiredMixin.no_permissions_fail returned a false-y value, the user lacking the permission would pass instead of being denied access.
    • Added doc for how to contribute.
    • Added MessageMixin to allow easier access to Django's contrib.messages messages. FormValidMessageMixin and FormInvalidMessageMixin were updated to use it.
    • Fixed bug in CanonicalSlugDetailMixin to allow it to use custom URL kwargs.
    • Fixed bug in GroupRequiredMixin where superusers were blocked by lack of group memberships.
    • Fixed bug in GroupRequiredMixin which now correctly checks for group membership against a list.
    • Added new StaticContextMixin mixin which lets you pass in static_context as a property of the view.
    • Added new AnonymousRequiredMixin which redirects authenticated users to another view.
    • Added new AllVerbsMixin which allows a single method to response to all HTTP verbs.
    • Provided JSONRequestResponseMixin as a mirror of JsonRequestResponseMixin because we're not PHP.
    • FormValidMessageMixin, FormInvalidMessageMixin, and FormMessagesMixin all allow ugettext_lazy-wrapped strings.
    • Extended PermissionRequiredMixin and MultiplePermissionsRequiredMixin to accept django-guardian-style custom/object permissions.
    Source code(tar.gz)
    Source code(zip)
  • v1.3.1(Jan 5, 2014)

  • v1.3.0(Jan 4, 2014)

    • Removed CreateAndRedirectToEditView mixin. It was marked for deprecation and removal since 1.0.
    • Added JsonRequestAndResponseMixin mixin which attempts to parse requests as JSON.
    • Added CanonicalSlugDetailMixin mixin which allows for the specification of a canonical slug on a DetailView to help with SEO by redirecting on non-canonical requests.
    • Added UserPassesTestMixin mixin to replicate the behavior of Django's @user_passes_test decorator.
    • Some fixes for CanonicalSlugDetailMixin.
    • AccessMixin now has a runtime-overridable login_url attribute.
    • Fixed problem with GroupRequiredMixin that made it not actually work.
    • All tests pass for Django versions 1.4 through 1.6 and Python versions 2.6, 2.7, and 3.3 (Django 1.4 and 1.5 not tested with Python 3.3).
    • Tests and documentation changes for all of the above.
    Source code(tar.gz)
    Source code(zip)
  • v1.2.2(Aug 7, 2013)

  • v1.2.1(Jul 28, 2013)

  • v1.2.0(Jul 27, 2013)

    • FormValidMessageMixin which provides a messages message when the processed form is valid.
    • FormInvalidMessageMixin which provides a messages message when the processed form is invalid.
    • FormMessagesMixin which provides the functionality of both of the above mixins.
    • GroupRequiredMixin which is a new access-level mixin which requires that a user be part of a specified group to access a view.
    Source code(tar.gz)
    Source code(zip)
  • v1.1.0(Jul 18, 2013)

    1.1.0 Release

    • JSONResponseMixin.render_json_response method updated to accept a status code.
    • JSONResponseMixin added json_dumps_kwargs attribute & get method to pass args to the json encoder.
    • New OrderableListMixin allows ordering of list views by GET params.
    • Tests updated to test against latest stable Django release (1.5.1)
    • Small fixes and additions to documentation.
    Source code(tar.gz)
    Source code(zip)
A Django web application that allows you to be in the loop about everything happening in your neighborhood.

A Django web application that allows you to be in the loop about everything happening in your neighborhood. From contact information of different handyman to meeting announcements or even alerts.

Kennedy Ngugi Mwaura 3 Dec 11, 2022
Utilities to make function-based views cleaner, more efficient, and better tasting.

django-fbv Utilities to make Django function-based views cleaner, more efficient, and better tasting. 💥 📖 Complete documentation: https://django-fbv

Adam Hill 49 Dec 30, 2022
Bootstrap 3 integration with Django.

django-bootstrap3 Bootstrap 3 integration for Django. Goal The goal of this project is to seamlessly blend Django and Bootstrap 3. Want to use Bootstr

Zostera B.V. 2.3k Jan 03, 2023
An app that allows you to add recipes from the dashboard made using DJango, JQuery, JScript and HTMl.

An app that allows you to add recipes from the dashboard. Then visitors filter based on different categories also each ingredient has a unique page with their related recipes.

Pablo Sagredo 1 Jan 31, 2022
A beginner django project and also my first Django project which involves shortening of a longer URL into a short one using a unique id.

Django-URL-Shortener A beginner django project and also my first Django project which involves shortening of a longer URL into a short one using a uni

Rohini Rao 3 Aug 08, 2021
PostgreSQL with Docker + Portainer + pgAdmin + Django local

django-postgresql-docker Running PostgreSQL with Docker + Portainer + pgAdmin + Django local for development. This project was done with: Python 3.9.8

Regis Santos 4 Jun 12, 2022
A pickled object field for Django

django-picklefield About django-picklefield provides an implementation of a pickled object field. Such fields can contain any picklable objects. The i

Gintautas Miliauskas 167 Oct 18, 2022
webfest Django project @innovaccer

inno-doctor webfest Django project @innovaccer setup guide create new directory for project clone the repo with url into the directory make sure pytho

Rohit sahu 6 Oct 28, 2022
Python CSS/Javascript minifier

Squeezeit - Python CSS and Javascript minifier Copyright (C) 2011 Sam Rudge This program is free software: you can redistribute it and/or modify it un

Smudge 152 Apr 03, 2022
Example project demonstrating using Django’s test runner with Coverage.py

Example project demonstrating using Django’s test runner with Coverage.py Set up with: python -m venv --prompt . venv source venv/bin/activate python

Adam Johnson 5 Nov 29, 2021
A Minimalistic Modern Django Boilerplate

A Minimalistic Modern Django Boilerplate This boilerplate is mainly for educational purposes. It is meant to be cloned as a starter code for future tu

Jonathan Adly 21 Nov 02, 2022
This is raw connection between redis server and django python app

Django_Redis This repository contains the code for this blogpost. Running the Application Clone the repository git clone https://github.com/xxl4tomxu9

Tom Xu 1 Sep 15, 2022
A Student/ School management application built using Django and Python.

Student Management An awesome student management app built using Django.! Explore the docs » View Demo · Report Bug · Request Feature Table of Content

Nishant Sethi 1 Feb 10, 2022
Zendesk Assignment - Django Based Ticket Viewer

Zendesk-Coding-Challenge Django Based Ticket Viewer The assignment has been made using Django. Important methods have been scripted in views.py. Excep

Akash Sampurnanand Pandey 0 Dec 23, 2021
Forgot password functionality build in Python / Django Rest Framework

Password Recover Recover password functionality with e-mail sender usign Django Email Backend How to start project. Create a folder in your machine Cr

alexandre Lopes 1 Nov 03, 2021
A Django app that creates automatic web UIs for Python scripts.

Wooey is a simple web interface to run command line Python scripts. Think of it as an easy way to get your scripts up on the web for routine data anal

Wooey 1.9k Jan 08, 2023
📝 Sticky Notes in Django admin

django-admin-sticky-notes Share notes between superusers. Installation Install via pip: pip install django_admin_sticky_notes Put django_admin_sticky_

Dariusz Choruży 7 Oct 06, 2021
Tutorial para o projeto negros.dev - A Essência do Django

Negros Dev Tutorial para o site negros.dev Este projeto foi feito com: Python 3.8.9 Django 3.1.8 Bootstrap 4.0 Como rodar o projeto? Clone esse reposi

Regis Santos 6 Aug 12, 2022
Django Pickled Model

Django Pickled Model Django pickled model provides you a model with dynamic data types. a field can store any value in any type. You can store Integer

Amir 3 Sep 14, 2022
Loguru is an exceeding easy way to do logging in Python

Django Easy Logging Easy Django logging with Loguru Loguru is an exceeding easy way to do logging in Python. django-easy-logging makes it exceedingly

Neutron Sync 8 Oct 17, 2022