/usr/lib/python2.7/dist-packages/braces/views.py is in python-django-braces 1.3.1-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 | import six
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.views import redirect_to_login
from django.core import serializers
from django.core.exceptions import ImproperlyConfigured, PermissionDenied
from django.core.serializers.json import DjangoJSONEncoder
from django.core.urlresolvers import resolve, reverse
from django.http import HttpResponse, HttpResponseBadRequest
from django.shortcuts import redirect
from django.utils.decorators import method_decorator
from django.utils.encoding import force_text
from django.views.decorators.csrf import csrf_exempt
## Django 1.5+ compat
try:
import json
except ImportError: # pragma: no cover
from django.utils import simplejson as json
class AccessMixin(object):
"""
'Abstract' mixin that gives access mixins the same customizable
functionality.
"""
login_url = None
raise_exception = False # Default whether to raise an exception to none
redirect_field_name = REDIRECT_FIELD_NAME # Set by django.contrib.auth
def get_login_url(self):
"""
Override this method to customize the login_url.
"""
login_url = self.login_url or settings.LOGIN_URL
if not login_url:
raise ImproperlyConfigured(
"Define %(cls)s.login_url or settings.LOGIN_URL or override "
"%(cls)s.get_login_url()." % {"cls": self.__class__.__name__})
return force_text(login_url)
def get_redirect_field_name(self):
"""
Override this method to customize the redirect_field_name.
"""
if self.redirect_field_name is None:
raise ImproperlyConfigured(
"%(cls)s is missing the "
"redirect_field_name. Define %(cls)s.redirect_field_name or "
"override %(cls)s.get_redirect_field_name()." % {
"cls": self.__class__.__name__})
return self.redirect_field_name
class LoginRequiredMixin(AccessMixin):
"""
View mixin which verifies that the user is authenticated.
NOTE:
This should be the left-most mixin of a view, except when
combined with CsrfExemptMixin - which in that case should
be the left-most mixin.
"""
def dispatch(self, request, *args, **kwargs):
if not request.user.is_authenticated():
if self.raise_exception:
raise PermissionDenied # return a forbidden response
else:
return redirect_to_login(request.get_full_path(),
self.get_login_url(),
self.get_redirect_field_name())
return super(LoginRequiredMixin, self).dispatch(
request, *args, **kwargs)
class CsrfExemptMixin(object):
"""
Exempts the view from CSRF requirements.
NOTE:
This should be the left-most mixin of a view.
"""
@method_decorator(csrf_exempt)
def dispatch(self, *args, **kwargs):
return super(CsrfExemptMixin, self).dispatch(*args, **kwargs)
class PermissionRequiredMixin(AccessMixin):
"""
View mixin which verifies that the logged in user has the specified
permission.
Class Settings
`permission_required` - the permission to check for.
`login_url` - the login url of site
`redirect_field_name` - defaults to "next"
`raise_exception` - defaults to False - raise 403 if set to True
Example Usage
class SomeView(PermissionRequiredMixin, ListView):
...
# required
permission_required = "app.permission"
# optional
login_url = "/signup/"
redirect_field_name = "hollaback"
raise_exception = True
...
"""
permission_required = None # Default required perms to none
def dispatch(self, request, *args, **kwargs):
# Make sure that the permission_required attribute is set on the
# view, or raise a configuration error.
if self.permission_required is None:
raise ImproperlyConfigured(
"'PermissionRequiredMixin' requires "
"'permission_required' attribute to be set.")
# Check to see if the request's user has the required permission.
has_permission = request.user.has_perm(self.permission_required)
if not has_permission: # If the user lacks the permission
if self.raise_exception: # *and* if an exception was desired
raise PermissionDenied # return a forbidden response.
else:
return redirect_to_login(request.get_full_path(),
self.get_login_url(),
self.get_redirect_field_name())
return super(PermissionRequiredMixin, self).dispatch(
request, *args, **kwargs)
class MultiplePermissionsRequiredMixin(AccessMixin):
"""
View mixin which allows you to specify two types of permission
requirements. The `permissions` attribute must be a dict which
specifies two keys, `all` and `any`. You can use either one on
its own or combine them. The value of each key is required to be a
list or tuple of permissions. The standard Django permissions
style is not strictly enforced. If you have created your own
permissions in a different format, they should still work.
By specifying the `all` key, the user must have all of
the permissions in the passed in list.
By specifying The `any` key , the user must have ONE of the set
permissions in the list.
Class Settings
`permissions` - This is required to be a dict with one or both
keys of `all` and/or `any` containing a list or tuple of
permissions.
`login_url` - the login url of site
`redirect_field_name` - defaults to "next"
`raise_exception` - defaults to False - raise 403 if set to True
Example Usage
class SomeView(MultiplePermissionsRequiredMixin, ListView):
...
#required
permissions = {
"all": ("blog.add_post", "blog.change_post"),
"any": ("blog.delete_post", "user.change_user")
}
#optional
login_url = "/signup/"
redirect_field_name = "hollaback"
raise_exception = True
"""
permissions = None # Default required perms to none
def dispatch(self, request, *args, **kwargs):
self._check_permissions_attr()
perms_all = self.permissions.get('all') or None
perms_any = self.permissions.get('any') or None
self._check_permissions_keys_set(perms_all, perms_any)
self._check_perms_keys("all", perms_all)
self._check_perms_keys("any", perms_any)
# If perms_all, check that user has all permissions in the list/tuple
if perms_all:
if not request.user.has_perms(perms_all):
if self.raise_exception:
raise PermissionDenied
return redirect_to_login(request.get_full_path(),
self.get_login_url(),
self.get_redirect_field_name())
# If perms_any, check that user has at least one in the list/tuple
if perms_any:
has_one_perm = False
for perm in perms_any:
if request.user.has_perm(perm):
has_one_perm = True
break
if not has_one_perm:
if self.raise_exception:
raise PermissionDenied
return redirect_to_login(request.get_full_path(),
self.get_login_url(),
self.get_redirect_field_name())
return super(MultiplePermissionsRequiredMixin, self).dispatch(
request, *args, **kwargs)
def _check_permissions_attr(self):
"""
Check permissions attribute is set and that it is a dict.
"""
if self.permissions is None or not isinstance(self.permissions, dict):
raise ImproperlyConfigured(
"'PermissionsRequiredMixin' requires "
"'permissions' attribute to be set to a dict.")
def _check_permissions_keys_set(self, perms_all=None, perms_any=None):
"""
Check to make sure the keys `any` or `all` are not both blank.
If both are blank either an empty dict came in or the wrong keys
came in. Both are invalid and should raise an exception.
"""
if perms_all is None and perms_any is None:
raise ImproperlyConfigured(
"'PermissionsRequiredMixin' requires"
"'permissions' attribute to be set to a dict and the 'any' "
"or 'all' key to be set.")
def _check_perms_keys(self, key=None, perms=None):
"""
If the permissions list/tuple passed in is set, check to make
sure that it is of the type list or tuple.
"""
if perms and not isinstance(perms, (list, tuple)):
raise ImproperlyConfigured(
"'MultiplePermissionsRequiredMixin' "
"requires permissions dict '%s' value to be a list "
"or tuple." % key)
class GroupRequiredMixin(AccessMixin):
group_required = None
def get_group_required(self):
if self.group_required is None or (
not isinstance(self.group_required,
(list, tuple) + six.string_types)
):
raise ImproperlyConfigured(
"'GroupRequiredMixin' requires "
"'group_required' attribute to be set and be one of the "
"following types: string, unicode, list, or tuple.")
return self.group_required
def check_membership(self, group):
""" Check required group(s) """
return group in self.request.user.groups.values_list("name", flat=True)
def dispatch(self, request, *args, **kwargs):
self.request = request
in_group = False
if self.request.user.is_authenticated():
in_group = self.check_membership(self.get_group_required())
if not in_group:
if self.raise_exception:
raise PermissionDenied
else:
return redirect_to_login(
request.get_full_path(),
self.get_login_url(),
self.get_redirect_field_name())
return super(GroupRequiredMixin, self).dispatch(
request, *args, **kwargs)
class UserPassesTestMixin(AccessMixin):
"""
CBV Mixin allows you to define test that every user should pass
to get access into view.
Class Settings
`test_func` - This is required to be a method that takes user
instance and return True or False after checking conditions.
`login_url` - the login url of site
`redirect_field_name` - defaults to "next"
`raise_exception` - defaults to False - raise 403 if set to True
"""
def test_func(self, user):
raise NotImplementedError(
"%(cls)s is missing implementation of the "
"test_func method. You should write one." % {
"cls": self.__class__.__name__})
def get_test_func(self):
return getattr(self, "test_func")
def dispatch(self, request, *args, **kwargs):
user_test_result = self.get_test_func()(request.user)
if not user_test_result: # If user don't pass the test
if self.raise_exception: # *and* if an exception was desired
raise PermissionDenied
else:
return redirect_to_login(request.get_full_path(),
self.get_login_url(),
self.get_redirect_field_name())
return super(UserPassesTestMixin, self).dispatch(
request, *args, **kwargs)
class UserFormKwargsMixin(object):
"""
CBV mixin which puts the user from the request into the form kwargs.
Note: Using this mixin requires you to pop the `user` kwarg
out of the dict in the super of your form's `__init__`.
"""
def get_form_kwargs(self):
kwargs = super(UserFormKwargsMixin, self).get_form_kwargs()
# Update the existing form kwargs dict with the request's user.
kwargs.update({"user": self.request.user})
return kwargs
class SuccessURLRedirectListMixin(object):
"""
Simple CBV mixin which sets the success url to the list view of
a given app. Set success_list_url as a class attribute of your
CBV and don't worry about overloading the get_success_url.
This is only to be used for redirecting to a list page. If you need
to reverse the url with kwargs, this is not the mixin to use.
"""
success_list_url = None # Default the success url to none
def get_success_url(self):
# Return the reversed success url.
if self.success_list_url is None:
raise ImproperlyConfigured(
"%(cls)s is missing a succes_list_url "
"name to reverse and redirect to. Define "
"%(cls)s.success_list_url or override "
"%(cls)s.get_success_url()"
"." % {"cls": self.__class__.__name__})
return reverse(self.success_list_url)
class SuperuserRequiredMixin(AccessMixin):
"""
Mixin allows you to require a user with `is_superuser` set to True.
"""
def dispatch(self, request, *args, **kwargs):
if not request.user.is_superuser: # If the user is a standard user,
if self.raise_exception: # *and* if an exception was desired
raise PermissionDenied # return a forbidden response.
else:
return redirect_to_login(request.get_full_path(),
self.get_login_url(),
self.get_redirect_field_name())
return super(SuperuserRequiredMixin, self).dispatch(
request, *args, **kwargs)
class SetHeadlineMixin(object):
"""
Mixin allows you to set a static headline through a static property on the
class or programmatically by overloading the get_headline method.
"""
headline = None # Default the headline to none
def get_context_data(self, **kwargs):
kwargs = super(SetHeadlineMixin, self).get_context_data(**kwargs)
# Update the existing context dict with the provided headline.
kwargs.update({"headline": self.get_headline()})
return kwargs
def get_headline(self):
if self.headline is None: # If no headline was provided as a view
# attribute and this method wasn't
# overridden raise a configuration error.
raise ImproperlyConfigured(
"%(cls)s is missing a headline. "
"Define %(cls)s.headline, or override "
"%(cls)s.get_headline()." % {"cls": self.__class__.__name__}
)
return self.headline
class SelectRelatedMixin(object):
"""
Mixin allows you to provide a tuple or list of related models to
perform a select_related on.
"""
select_related = None # Default related fields to none
def get_queryset(self):
if self.select_related is None: # If no fields were provided,
# raise a configuration error
raise ImproperlyConfigured(
"%(cls)s is missing the "
"select_related property. This must be a tuple or list." % {
"cls": self.__class__.__name__})
if not isinstance(self.select_related, (tuple, list)):
# If the select_related argument is *not* a tuple or list,
# raise a configuration error.
raise ImproperlyConfigured(
"%(cls)s's select_related property "
"must be a tuple or list." % {"cls": self.__class__.__name__})
# Get the current queryset of the view
queryset = super(SelectRelatedMixin, self).get_queryset()
return queryset.select_related(*self.select_related)
class PrefetchRelatedMixin(object):
"""
Mixin allows you to provide a tuple or list of related models to
perform a prefetch_related on.
"""
prefetch_related = None # Default prefetch fields to none
def get_queryset(self):
if self.prefetch_related is None: # If no fields were provided,
# raise a configuration error
raise ImproperlyConfigured(
"%(cls)s is missing the "
"prefetch_related property. This must be a tuple or list." % {
"cls": self.__class__.__name__})
if not isinstance(self.prefetch_related, (tuple, list)):
# If the select_related argument is *not* a tuple or list,
# raise a configuration error.
raise ImproperlyConfigured(
"%(cls)s's prefetch_related property "
"must be a tuple or list." % {"cls": self.__class__.__name__})
# Get the current queryset of the view
queryset = super(PrefetchRelatedMixin, self).get_queryset()
return queryset.prefetch_related(*self.prefetch_related)
class StaffuserRequiredMixin(AccessMixin):
"""
Mixin allows you to require a user with `is_staff` set to True.
"""
def dispatch(self, request, *args, **kwargs):
if not request.user.is_staff: # If the request's user is not staff,
if self.raise_exception: # *and* if an exception was desired
raise PermissionDenied # return a forbidden response
else:
return redirect_to_login(request.get_full_path(),
self.get_login_url(),
self.get_redirect_field_name())
return super(StaffuserRequiredMixin, self).dispatch(
request, *args, **kwargs)
class JSONResponseMixin(object):
"""
A mixin that allows you to easily serialize simple data such as a dict or
Django models.
"""
content_type = u"application/json"
json_dumps_kwargs = None
def get_content_type(self):
if self.content_type is None:
raise ImproperlyConfigured(
u"%(cls)s is missing a content type. "
u"Define %(cls)s.content_type, or override "
u"%(cls)s.get_content_type()." % {
u"cls": self.__class__.__name__}
)
return self.content_type
def get_json_dumps_kwargs(self):
if self.json_dumps_kwargs is None:
self.json_dumps_kwargs = {}
self.json_dumps_kwargs.setdefault(u'ensure_ascii', False)
return self.json_dumps_kwargs
def render_json_response(self, context_dict, status=200):
"""
Limited serialization for shipping plain data. Do not use for models
or other complex or custom objects.
"""
json_context = json.dumps(context_dict, cls=DjangoJSONEncoder,
**self.get_json_dumps_kwargs()).encode(
u'utf-8')
return HttpResponse(json_context,
content_type=self.get_content_type(),
status=status)
def render_json_object_response(self, objects, **kwargs):
"""
Serializes objects using Django's builtin JSON serializer. Additional
kwargs can be used the same way for django.core.serializers.serialize.
"""
json_data = serializers.serialize(u"json", objects, **kwargs)
return HttpResponse(json_data, content_type=self.get_content_type())
class AjaxResponseMixin(object):
"""
Mixin allows you to define alternative methods for ajax requests. Similar
to the normal get, post, and put methods, you can use get_ajax, post_ajax,
and put_ajax.
"""
def dispatch(self, request, *args, **kwargs):
request_method = request.method.lower()
if request.is_ajax() and request_method in self.http_method_names:
handler = getattr(self, u"{0}_ajax".format(request_method),
self.http_method_not_allowed)
self.request = request
self.args = args
self.kwargs = kwargs
return handler(request, *args, **kwargs)
return super(AjaxResponseMixin, self).dispatch(
request, *args, **kwargs)
def get_ajax(self, request, *args, **kwargs):
return self.get(request, *args, **kwargs)
def post_ajax(self, request, *args, **kwargs):
return self.post(request, *args, **kwargs)
def put_ajax(self, request, *args, **kwargs):
return self.get(request, *args, **kwargs)
def delete_ajax(self, request, *args, **kwargs):
return self.get(request, *args, **kwargs)
class JsonRequestResponseMixin(JSONResponseMixin):
"""
Extends JSONResponseMixin. Attempts to parse request as JSON. If request
is properly formatted, the json is saved to self.request_json as a Python
object. request_json will be None for imparsible requests.
Set the attribute require_json to True to return a 400 "Bad Request" error
for requests that don't contain JSON.
Note: To allow public access to your view, you'll need to use the
csrf_exempt decorator or CsrfExemptMixin.
Example Usage:
class SomeView(CsrfExemptMixin, JsonRequestResponseMixin):
def post(self, request, *args, **kwargs):
do_stuff_with_contents_of_request_json()
return self.render_json_response(
{'message': 'Thanks!'})
"""
require_json = False
error_response_dict = {u"errors": [u"Improperly formatted request"]}
def render_bad_request_response(self, error_dict=None):
if error_dict is None:
error_dict = self.error_response_dict
json_context = json.dumps(
error_dict,
cls=DjangoJSONEncoder,
**self.get_json_dumps_kwargs()
).encode(u'utf-8')
return HttpResponseBadRequest(
json_context, content_type=self.get_content_type())
def get_request_json(self):
try:
return json.loads(self.request.body.decode(u'utf-8'))
except ValueError:
return None
def dispatch(self, request, *args, **kwargs):
self.request = request
self.args = args
self.kwargs = kwargs
self.request_json = self.get_request_json()
if self.require_json and self.request_json is None:
return self.render_bad_request_response()
return super(JsonRequestResponseMixin, self).dispatch(
request, *args, **kwargs)
class OrderableListMixin(object):
"""
Mixin allows your users to order records using GET parameters
"""
orderable_columns = None
orderable_columns_default = None
order_by = None
ordering = None
def get_context_data(self, **kwargs):
"""
Augments context with:
* ``order_by`` - name of the field
* ``ordering`` - order of ordering, either ``asc`` or ``desc``
"""
context = super(OrderableListMixin, self).get_context_data(**kwargs)
context["order_by"] = self.order_by
context["ordering"] = self.ordering
return context
def get_orderable_columns(self):
if not self.orderable_columns:
raise ImproperlyConfigured(
"Please define allowed ordering columns")
return self.orderable_columns
def get_orderable_columns_default(self):
if not self.orderable_columns_default:
raise ImproperlyConfigured("Please define default ordering column")
return self.orderable_columns_default
def get_ordered_queryset(self, queryset=None):
"""
Augments ``QuerySet`` with order_by statement if possible
:param QuerySet queryset: ``QuerySet`` to ``order_by``
:return: QuerySet
"""
get_order_by = self.request.GET.get("order_by")
if get_order_by in self.get_orderable_columns():
order_by = get_order_by
else:
order_by = self.get_orderable_columns_default()
self.order_by = order_by
self.ordering = "asc"
if order_by and self.request.GET.get("ordering", "asc") == "desc":
order_by = "-" + order_by
self.ordering = "desc"
return queryset.order_by(order_by)
def get_queryset(self):
"""
Returns ordered ``QuerySet``
"""
unordered_queryset = super(OrderableListMixin, self).get_queryset()
return self.get_ordered_queryset(unordered_queryset)
class CanonicalSlugDetailMixin(object):
"""
A mixin that enforces a canonical slug in the url.
If a urlpattern takes a object's pk and slug as arguments and the slug url
argument does not equal the object's canonical slug, this mixin will
redirect to the url containing the canonical slug.
"""
def dispatch(self, request, *args, **kwargs):
# Set up since we need to super() later instead of earlier.
self.request = request
self.args = args
self.kwargs = kwargs
# Get the current object, url slug, and
# urlpattern name (namespace aware).
obj = self.get_object()
slug = self.kwargs.get(self.slug_url_kwarg, None)
match = resolve(request.path_info)
url_parts = match.namespaces
url_parts.append(match.url_name)
current_urlpattern = ":".join(url_parts)
# Figure out what the slug is supposed to be.
if hasattr(obj, "get_canonical_slug"):
canonical_slug = obj.get_canonical_slug()
else:
canonical_slug = self.get_canonical_slug()
# If there's a discrepancy between the slug in the url and the
# canonical slug, redirect to the canonical slug.
if canonical_slug != slug:
return redirect(current_urlpattern, pk=obj.pk, slug=canonical_slug,
permanent=True)
return super(CanonicalSlugDetailMixin, self).dispatch(
request, *args, **kwargs)
def get_canonical_slug(self):
"""
Override this method to customize what slug should be considered
canonical.
Alternatively, define the get_canonical_slug method on this view's
object class. In that case, this method will never be called.
"""
return self.get_object().slug
class FormValidMessageMixin(object):
"""
Mixin allows you to set static message which is displayed by
Django's messages framework through a static property on the class
or programmatically by overloading the get_form_valid_message method.
"""
form_valid_message = None # Default to None
def get_form_valid_message(self):
"""
Validate that form_valid_message is set and is either a
unicode or str object.
"""
if self.form_valid_message is None:
raise ImproperlyConfigured(
'{0}.form_valid_message is not set. Define '
'{0}.form_valid_message, or override '
'{0}.get_form_valid_message().'.format(self.__class__.__name__)
)
if not isinstance(self.form_valid_message, six.string_types):
raise ImproperlyConfigured(
'{0}.form_valid_message must be a str or unicode '
'object.'.format(self.__class__.__name__)
)
return self.form_valid_message
def form_valid(self, form):
"""
Call the super first, so that when overriding
get_form_valid_message, we have access to the newly saved object.
"""
response = super(FormValidMessageMixin, self).form_valid(form)
messages.success(self.request, self.get_form_valid_message(),
fail_silently=True)
return response
class FormInvalidMessageMixin(object):
"""
Mixin allows you to set static message which is displayed by
Django's messages framework through a static property on the class
or programmatically by overloading the get_form_invalid_message method.
"""
form_invalid_message = None
def get_form_invalid_message(self):
"""
Validate that form_invalid_message is set and is either a
unicode or str object.
"""
if self.form_invalid_message is None:
raise ImproperlyConfigured(
'{0}.form_invalid_message is not set. Define '
'{0}.form_invalid_message, or override '
'{0}.get_form_invalid_message().'.format(
self.__class__.__name__)
)
if not isinstance(self.form_invalid_message,
(six.string_types, six.text_type)):
raise ImproperlyConfigured(
'{0}.form_invalid_message must be a str or unicode '
'object.'.format(self.__class__.__name__)
)
return self.form_invalid_message
def form_invalid(self, form):
response = super(FormInvalidMessageMixin, self).form_invalid(form)
messages.error(self.request, self.get_form_invalid_message(),
fail_silently=True)
return response
class FormMessagesMixin(FormValidMessageMixin, FormInvalidMessageMixin):
"""
Mixin is a shortcut to use both FormValidMessageMixin and
FormInvalidMessageMixin.
"""
pass
|