Reusable, generic mixins for Django class-based views
npx @tessl/cli install tessl/pypi-django-braces@1.17.00
# Django Braces
1
2
Django Braces provides a comprehensive collection of reusable mixins for Django's class-based views. Most mixins replicate the behavior of Django's function-based view decorators, while others solve common headaches with class-based views. The library offers 24 view mixins and 1 form mixin organized into functional categories for authentication, AJAX handling, form processing, caching, and query optimization.
3
4
## Package Information
5
6
- **Package Name**: django-braces
7
- **Language**: Python
8
- **Installation**: `pip install django-braces`
9
- **Django Compatibility**: 2.2-4.2
10
- **Python Compatibility**: 3.6-3.13
11
12
## Core Imports
13
14
```python
15
from braces.views import LoginRequiredMixin, JSONResponseMixin, MessageMixin
16
```
17
18
For form mixins:
19
20
```python
21
from braces.forms import UserKwargModelFormMixin
22
```
23
24
## Basic Usage
25
26
```python
27
from django.views.generic import ListView, CreateView
28
from braces.views import LoginRequiredMixin, JSONResponseMixin, MessageMixin
29
30
# Simple authentication requirement
31
class ProtectedListView(LoginRequiredMixin, ListView):
32
model = MyModel
33
login_url = '/login/'
34
35
# AJAX-enabled view with JSON responses
36
class AjaxDataView(JSONResponseMixin, ListView):
37
model = MyModel
38
39
def get(self, request, *args, **kwargs):
40
if request.headers.get('x-requested-with') == 'XMLHttpRequest':
41
data = list(self.get_queryset().values('id', 'name'))
42
return self.render_json_response({'results': data})
43
return super().get(request, *args, **kwargs)
44
45
# Form with success messages
46
class CreateWithMessageView(MessageMixin, CreateView):
47
model = MyModel
48
49
def form_valid(self, form):
50
response = super().form_valid(form)
51
self.messages.success('Item created successfully!')
52
return response
53
```
54
55
## Architecture
56
57
Django Braces uses Python's multiple inheritance to add functionality to Django's class-based views. Each mixin focuses on a specific concern and can be combined with other mixins and Django's generic views:
58
59
- **Access Mixins**: Authentication and authorization controls
60
- **AJAX Mixins**: AJAX request handling and JSON responses
61
- **Form Mixins**: Form processing enhancements and messaging
62
- **Utility Mixins**: Context manipulation and HTTP header management
63
- **Query Mixins**: Database query optimization helpers
64
65
Mixins are designed to be combined safely, with clear inheritance order requirements documented for each mixin.
66
67
## Capabilities
68
69
### Access Control and Authentication
70
71
Authentication requirements, permission checking, group membership validation, and secure connection enforcement. These mixins provide the building blocks for securing Django class-based views.
72
73
```python { .api }
74
class LoginRequiredMixin:
75
login_url = None
76
raise_exception = False
77
redirect_field_name = 'next'
78
79
class PermissionRequiredMixin:
80
permission_required = None
81
object_level_permissions = False
82
83
class GroupRequiredMixin:
84
group_required = None
85
```
86
87
[Access Control](./access-control.md)
88
89
### AJAX and JSON Response Handling
90
91
AJAX request detection, JSON response generation, and request body parsing. These mixins enable seamless AJAX integration with class-based views.
92
93
```python { .api }
94
class JSONResponseMixin:
95
content_type = None
96
json_dumps_kwargs = None
97
json_encoder_class = None
98
99
class AjaxResponseMixin:
100
def get_ajax(self, request, *args, **kwargs): ...
101
def post_ajax(self, request, *args, **kwargs): ...
102
```
103
104
[AJAX and JSON](./ajax-json.md)
105
106
### Form Processing and Messaging
107
108
Form validation messages, CSRF exemption, user context injection, and success URL handling. These mixins enhance Django's form processing capabilities.
109
110
```python { .api }
111
class MessageMixin:
112
messages = _MessageDescriptor()
113
114
class FormValidMessageMixin:
115
form_valid_message = None
116
def get_form_valid_message(self): ...
117
118
class UserFormKwargsMixin:
119
def get_form_kwargs(self): ...
120
```
121
122
[Form Processing](./form-processing.md)
123
124
### HTTP and Caching Utilities
125
126
HTTP header manipulation, cache control, context enhancement, and URL canonicalization. These mixins provide essential web development utilities.
127
128
```python { .api }
129
class HeaderMixin:
130
headers = {}
131
def get_headers(self, request): ...
132
133
class CacheControlMixin:
134
cachecontrol_max_age = None
135
cachecontrol_public = None
136
cachecontrol_private = None
137
cachecontrol_no_cache = None
138
cachecontrol_must_revalidate = None
139
```
140
141
[HTTP Utilities](./http-utilities.md)
142
143
### Database Query Optimization
144
145
Query optimization through select_related, prefetch_related, and dynamic ordering. These mixins improve database performance in list views.
146
147
```python { .api }
148
class SelectRelatedMixin:
149
select_related = None
150
def get_queryset(self): ...
151
152
class OrderableListMixin:
153
orderable_columns = None
154
orderable_columns_default = None
155
ordering_default = None
156
order_by = None
157
ordering = None
158
```
159
160
[Query Optimization](./query-optimization.md)
161
162
### Form Enhancement
163
164
Form validation helpers and user context injection for enhanced form handling in class-based views.
165
166
```python { .api }
167
class UserKwargModelFormMixin:
168
user = None
169
170
def __init__(self, *args, **kwargs):
171
"""Remove user from kwargs and assign to instance"""
172
```
173
174
This form mixin is available directly from `braces.forms` and is documented within the Form Processing section above.