python Django Mixins
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Django Mixins相关的知识,希望对你有一定的参考价值。
import json
from django.http import HttpResponse
from django.views.generic.edit import CreateView
from django.contrib.auth.decorators import user_passes_test
from django.utils.decorators import method_decorator
class StaffRequiredMixin(object):
@method_decorator(user_passes_test(lambda u: u.is_staff))
def dispatch(self, *args, **kwargs):
return super(StaffRequiredMixin, self).dispatch(*args, **kwargs)
class SuperuserRequiredMixin(object):
@method_decorator(user_passes_test(lambda u: u.is_superuser))
def dispatch(self, *args, **kwargs):
return super(SuperuserRequiredMixin, self).dispatch(*args, **kwargs)
class AjaxableResponseMixin(object):
"""
Mixin to add AJAX support to a form.
Must be used with an object-based FormView (e.g. CreateView)
"""
def render_to_json_response(self, context, **response_kwargs):
data = json.dumps(context)
response_kwargs['content_type'] = 'application/json'
return HttpResponse(data, **response_kwargs)
def form_invalid(self, form):
response = super(AjaxableResponseMixin, self).form_invalid(form)
if self.request.is_ajax():
return self.render_to_json_response(form.errors, status=400)
else:
return response
def form_valid(self, form):
# We make sure to call the parent's form_valid() method because
# it might do some processing (in the case of CreateView, it will
# call form.save() for example).
response = super(AjaxableResponseMixin, self).form_valid(form)
if self.request.is_ajax():
data = {
'pk': self.object.pk,
}
return self.render_to_json_response(data)
else:
return response
class AsDictionaryMixin:
def to_dict(self):
return {
prop: self._represent(value)
for prop, value in self.__dict__.items()
if not self._is_internal(prop)
}
def _represent(self, value):
if isinstance(value, object):
if hasattr(value, 'to_dict'):
return value.to_dict()
else:
return str(value)
else:
return value
def _is_internal(self, prop):
return prop.startswith('_')
class MultiRedirectMixin(object):
"""
A mixin that supports submit-specific success redirection.
Either specify one success_url, or provide dict with names of
submit actions given in template as keys
Example:
In template:
<input type="submit" name="create_new" value="Create"/>
<input type="submit" name="delete" value="Delete"/>
View:
MyMultiSubmitView(MultiRedirectMixin, forms.FormView):
success_urls = {"create_new": reverse_lazy('create'),
"delete": reverse_lazy('delete')}
"""
success_urls = {}
def form_valid(self, form):
""" Form is valid: Pick the url and redirect.
"""
for name in self.success_urls:
if name in form.data:
self.success_url = self.success_urls[name]
break
return HttpResponseRedirect(self.get_success_url())
# def get_success_url(self):
# """
# Returns the supplied success URL.
# """
# if self.success_url:
# # Forcing possible reverse_lazy evaluation
# url = force_text(self.success_url)
# else:
# raise ImproperlyConfigured(
# _("No URL to redirect to. Provide a success_url."))
# return url
以上是关于python Django Mixins的主要内容,如果未能解决你的问题,请参考以下文章
Django Model Mixins:继承自models.Model还是对象?