Created
February 17, 2011 12:31
-
-
Save k1000/831623 to your computer and use it in GitHub Desktop.
ajax form using partials taking advantage of class views (new in django 1.3)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from django import forms | |
from django.views.generic.edit import FormView | |
from django.utils.translation import ugettext_lazy as _ | |
from django.utils.translation import force_unicode | |
from ajax import JSONResponseMixin, JSONResponsePartialMixin | |
class HoneySpotMixin(object): | |
error_css_class = 'error' | |
required_css_class = 'required' | |
def clean_name(self): | |
#if not 'name' in self.cleaned_data: | |
if 'name' in self.cleaned_data: | |
if self.cleaned_data['name'] is not u'': | |
raise forms.ValidationError(u'Leave the "name" field empty!') | |
MSG_FAIL = _("Hay errores en los datos enviados") | |
MSG_SUCCESS = _("Gracias por su interes. Pronto contactaremos con Usted.") | |
class AjaxFormView( JSONResponseMixin, FormView ): | |
""" | |
Ajax form view which returns json with list of errors | |
ussage:: | |
class ContatView( AjaxPartialFormView ): | |
form_class = ContactForm | |
template_name = "contact/contact.html" | |
""" | |
partial_var_name = "form" | |
def form_valid(self, form): | |
if self.request.is_ajax(): | |
context = self.get_context_data( form_valid=1, message= MSG_SUCCESS) | |
return self.render_to_response( context ) | |
else: | |
return super( AjaxFormView, self).form_valid(form) | |
def form_invalid(self, form): | |
errors = [(k, force_unicode( v[0]) ) for k, v in form.errors.items()] | |
context = self.get_context_data( form_valid=0, message= MSG_FAIL, errors = errors ) | |
return self.render_to_response( context ) | |
def render_to_response(self, context): | |
if self.request.is_ajax(): | |
return JSONResponseMixin.render_to_response(self, context) | |
else: | |
return FormView.render_to_response(self, context) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment