Doing some experiments to try out the power of class-based views on Django 1.3, I came up with a pretty neat solution for adding flash messages and notifications when working with forms.
I must first say that the notifications framework used is the one bundled with Pinax.
The Code
from django.views.generic.edit import CreateView
from django.contrib import messages
if "notification" in getattr(settings, "INSTALLED_APPS"):
from notification import models as notification
else:
notification = None
class NotifyMixin(object):
valid_type = messages.SUCCESS
valid_message = None
valid_flash = True
invalid_type = messages.ERROR
invalid_message = _("Some validation errors where found on the submitted form.")
invalid_flash = True
notify_list = None
notify_template = None
def show_invalid_flash(self):
if self.invalid_flash:
messages.add_message(self.request, self.invalid_type, self.invalid_message)
def show_valid_flash(self):
self.valid_message = _("The %s has been added successfully" % self.object._meta.verbose_name)
if self.valid_flash:
messages.add_message(self.request, self.valid_type, self.valid_message)
def send_notification(self):
if notification and self.notify_list and self.notify_template:
notification.send(self.notify_list,
self.notify_template,
self.get_context_data())
class NotifyCreateView(CreateView, NotifyMixin):
def form_valid(self, form):
ret = super(NotifyCreateView, self).form_valid(form)
self.show_valid_flash()
self.send_notification()
return ret
def form_invalid(self, form, **kwargs):
show_invalid_flash()
return self.render_to_response(self.get_context_data(form=form))
Example usage
An example usage for a generic create view without notifications framework would be something like this:
class ProjectCreate(NotifyCreateView):
login_required = True
form_class = ProjectForm
Just getting started with class-based stuff on Django and loving the power of inheritance ;)
Comments and suggestions... always welcome!
|