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)
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 04, 2023
Django Phyton Web Apps template themes

Django Phyton Web Apps template themes Free download source code project for build a modern website using django phyton web apps. Documentation instal

Mesin Kasir 4 Dec 15, 2022
An API was build with Django to store and retrieve information about various musical instruments.

The project is meant to be a starting point, an experimentation or a basic example of a way to develop an API with Django. It is an exercise on using Django and various python technologies and design

Kostas Ziovas 2 Dec 25, 2021
Silk is a live profiling and inspection tool for the Django framework.

Silk is a live profiling and inspection tool for the Django framework. Silk intercepts and stores HTTP requests and database queries before presenting them in a user interface for further inspection:

Jazzband 3.7k Jan 02, 2023
Learn Python and the Django Framework by building a e-commerce website

The Django-Ecommerce is an open-source project initiative and tutorial series built with Python and the Django Framework.

Very Academy 275 Jan 08, 2023
Agenda feita usando o django para adicionar eventos

Agenda de Eventos Projeto Agenda com Django Inicio O projeto foi iniciado no Django, usando o models.py foi adicionado os dados dos eventos e feita as

Bruno Fernandes 1 Apr 14, 2022
GeoDjango provides geospatial extensions to the Django web dev framework

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. All documentation is in the "docs" directo

Paul Smith 20 Sep 20, 2022
Django based webapp pulling in crypto news and price data via api

Deploy Django in Production FTA project implementing containerization of Django Web Framework into Docker to be placed into Azure Container Services a

0 Sep 21, 2022
Django-Audiofield is a simple app that allows Audio files upload, management and conversion to different audio format (mp3, wav & ogg), which also makes it easy to play audio files into your Django application.

Django-Audiofield Description: Django Audio Management Tools Maintainer: Areski Contributors: list of contributors Django-Audiofield is a simple app t

Areski Belaid 167 Nov 10, 2022
Returns unicode slugs

Python Slugify A Python slugify application that handles unicode. Overview Best attempt to create slugs from unicode strings while keeping it DRY. Not

Val Neekman (AvidCoder) 1.3k Dec 23, 2022
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
Add a help desk or knowledge base to your Django project with only a few lines of boilerplate code.

This project is no longer maintained. If you are interested in taking over the project, email Zapier 487 Dec 06, 2022

This is a basic Todo Application API using Django Rest Framework

Todo Application This is a basic Todo Application API using Django Rest Framework. Todo Section - User can View his previously added todo items, creat

Atharva Parkhe 1 Aug 09, 2022
Django REST Client API

Django REST Client API Client data provider API.

Ulysses Monteiro 1 Nov 08, 2021
PicoStyle - Advance market place website written in django

Advance market place website written in django :) Online fashion store for whole

AminAli Mazarian 26 Sep 10, 2022
A calendaring app for Django. It is now stable, Please feel free to use it now. Active development has been taken over by bartekgorny.

Django-schedule A calendaring/scheduling application, featuring: one-time and recurring events calendar exceptions (occurrences changed or cancelled)

Tony Hauber 814 Dec 26, 2022
🏭 An easy-to-use implementation of Creation Methods for Django, backed by Faker.

Django-fakery An easy-to-use implementation of Creation Methods (aka Object Factory) for Django, backed by Faker. django_fakery will try to guess the

Flavio Curella 93 Oct 12, 2022
Wrap the Blockchain API in Django!

django-blockchain Wrap the Blockchain API in Django. Installation pip install django-blockchain Add app in your settings.py INSTALLED_APPS = [ "d

Dmitry Kalinin 2 Feb 04, 2022
A GitHub Action for checking Django migrations

🔍 Django migrations checker A GitHub Action for checking Django migrations About This repository contains a Github Action that checks Django migratio

Oda 5 Nov 15, 2022
Custom Django field for using enumerations of named constants

django-enumfield Provides an enumeration Django model field (using IntegerField) with reusable enums and transition validation. Installation Currently

5 Monkeys 195 Dec 20, 2022