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 reusable Django model field for storing ad-hoc JSON data

jsonfield jsonfield is a reusable model field that allows you to store validated JSON, automatically handling serialization to and from the database.

Ryan P Kilby 1.1k Jan 3, 2023
Reusable workflow library for Django

django-viewflow Viewflow is a lightweight reusable workflow library that helps to organize people collaboration business logic in django applications.

Viewflow 2.3k Jan 8, 2023
Build reusable components in Django without writing a single line of Python.

Build reusable components in Django without writing a single line of Python. {% #quote %} {% quote_photo src="/project-hail-mary.jpg" %} {% #quot

Mitchel Cabuloy 277 Jan 2, 2023
A reusable Django app that configures your project for deployment

django-simple-deploy This app gives you a management command that configures your project for an initial deployment. It targets Heroku at the moment,

Eric Matthes 205 Dec 26, 2022
A generic system for filtering Django QuerySets based on user selections

Django Filter Django-filter is a reusable Django application allowing users to declaratively add dynamic QuerySet filtering from URL parameters. Full

Carlton Gibson 3.9k Jan 3, 2023
Django's class-based generic views are awesome, let's have more of them.

Django Extra Views - The missing class-based generic views for Django Django-extra-views is a Django package which introduces additional class-based v

Andy Ingram 1.3k Jan 4, 2023
Generate generic activity streams from the actions on your site. Users can follow any actors' activities for personalized streams.

Django Activity Stream What is Django Activity Stream? Django Activity Stream is a way of creating activities generated by the actions on your site. I

Justin Quick 2.1k Dec 29, 2022
Django URL Shortener is a Django app to to include URL Shortening feature in your Django Project

Django URL Shortener Django URL Shortener is a Django app to to include URL Shortening feature in your Django Project Install this package to your Dja

Rishav Sinha 4 Nov 18, 2021
Meta package to combine turbo-django and stimulus-django

Hotwire + Django This repository aims to help you integrate Hotwire with Django ?? Inspiration might be taken from @hotwired/hotwire-rails. We are sti

Hotwire for Django 31 Aug 9, 2022
django-reversion is an extension to the Django web framework that provides version control for model instances.

django-reversion django-reversion is an extension to the Django web framework that provides version control for model instances. Requirements Python 3

Dave Hall 2.8k Jan 2, 2023
Django-environ allows you to utilize 12factor inspired environment variables to configure your Django application.

Django-environ django-environ allows you to use Twelve-factor methodology to configure your Django application with environment variables. import envi

Daniele Faraglia 2.7k Jan 7, 2023
Rosetta is a Django application that eases the translation process of your Django projects

Rosetta Rosetta is a Django application that facilitates the translation process of your Django projects. Because it doesn't export any models, Rosett

Marco Bonetti 909 Dec 26, 2022
Cookiecutter Django is a framework for jumpstarting production-ready Django projects quickly.

Cookiecutter Django Powered by Cookiecutter, Cookiecutter Django is a framework for jumpstarting production-ready Django projects quickly. Documentati

Daniel Feldroy 10k Dec 31, 2022
Django project starter on steroids: quickly create a Django app AND generate source code for data models + REST/GraphQL APIs (the generated code is auto-linted and has 100% test coverage).

Create Django App ?? We're a Django project starter on steroids! One-line command to create a Django app with all the dependencies auto-installed AND

imagine.ai 68 Oct 19, 2022
django-quill-editor makes Quill.js easy to use on Django Forms and admin sites

django-quill-editor django-quill-editor makes Quill.js easy to use on Django Forms and admin sites No configuration required for static files! The ent

lhy 139 Dec 5, 2022
A Django chatbot that is capable of doing math and searching Chinese poet online. Developed with django, channels, celery and redis.

Django Channels Websocket Chatbot A Django chatbot that is capable of doing math and searching Chinese poet online. Developed with django, channels, c

Yunbo Shi 8 Oct 28, 2022
A handy tool for generating Django-based backend projects without coding. On the other hand, it is a code generator of the Django framework.

Django Sage Painless The django-sage-painless is a valuable package based on Django Web Framework & Django Rest Framework for high-level and rapid web

sageteam 51 Sep 15, 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 8, 2021
Dockerizing Django with Postgres, Gunicorn, Nginx and Certbot. A fully Django starter project.

Dockerizing Django with Postgres, Gunicorn, Nginx and Certbot ?? Features A Django stater project with fully basic requirements for a production-ready

null 8 Jun 27, 2022