Anonymous avatar Anonymous committed 7d0a461

Custom error mesage for the form

Comments (0)

Files changed (3)

 # -*- coding: utf-8 -*-
 from django import forms
 from django.forms.util import ErrorList
+from django.utils.encoding import smart_unicode, StrAndUnicode, force_unicode
+from django.utils.safestring import mark_safe
 from django.contrib.formtools.preview import FormPreview,AUTO_ID
 from django.http import HttpResponseRedirect
 from django.shortcuts import render_to_response
                 return self.failed_hash(request) # Security hash failed.
             return self.done(request, f.cleaned_data)
         else:
+            print f.errors  # HDKNR
             return render_to_response(self.form_template,
                 {'form': f, 'stage_field': self.unused_name('stage'), 'state': self.state},
                 context_instance=RequestContext(request))
 
 
+
 class SignupForm(forms.ModelForm):
+    class SignupFormError(ErrorList):
+        def __unicode__(self):
+            return self.as_span()
+        def as_divs(self):
+            if not self: return u''
+            return mark_safe( u'<div class="errorlist">%s</div>' % ''.join([u'<div class="error" >%s</div>' % e for e in self]))
+        def as_span(self):
+            if not self: return u''
+            return mark_safe( u'<span class="errorlist">%s</span>' % ''.join([u'<span class="error" >%s</span>' % force_unicode(e) for e in self]))
+
     email_confirm = forms.CharField(widget=forms.widgets.Input)
     password = forms.CharField(widget=forms.PasswordInput )
     password_confirm = forms.CharField(widget=forms.PasswordInput )
 
+    def __init__(self,*args,**kwargs):
+        super(SignupForm,self).__init__(*args,**kwargs)         # superclass.__init__(self,...)
+        self.error_class = SignupForm.SignupFormError 
+
     def is_valid(self):
+        def is_katakana(src):
+            r = re.search(r'^(\xe3(\x82[\xa1-\xbf]|\x83[\x80-\xb6]|\x83[\xbb-\xbe]))+$',src.encode('utf8')) 
+            return ( r != None )
+            
         valid = super(SignupForm,self).is_valid()
-        if self.data[u'password'] != self.data[u'password_confirm']  :
-            self._errors[u'password_confirm'] = ErrorList([u'パスワードが一致しません'])
+
+        for i in ['kana01','kana02']:
+            data =  self.data[i]
+            if  len(data) and is_katakana(data ) == False:
+                print i,"invalid......"
+#                print self._errors[i]
+                print self._errors.keys()
+                self._errors['kana01'] = ErrorList(['カタカナで入力してください'])
+                print self._errors.keys()
+                valid=False
+
+        if self.data['password'] != self.data[u'password_confirm']  :
+            self._errors['password_confirm'] = self.error_class(['パスワードが一致しません'])
             valid = False
 
-        if self.data[u'email'] != self.data[u'email_confirm'] :
-            self._errors[u'email_confirm'] = ErrorList([u'メールアドレスが一致しません'])
+        if self.data['email'] != self.data['email_confirm'] :
+            self._errors['email_confirm'] = self.error_class(['メールアドレスが一致しません'])
             valid = False
+
         return valid 
 
     class Meta:
     preview_template = 'djcube/signup_preview.html'
     form_template = 'djcube/signup.html'
 
+    @classmethod
+    def dispatcher(cls):
+        return cls( SignupForm )
+
     def done(self, request, cleaned_data):
-        print "done.....",dir(self.form)
         # Do something with the cleaned_data, then redirect
         # to a "success" page.
         params = cleaned_data.copy()
         m.register()
         m.save()
         return HttpResponseRedirect('/')
-#
 
-#class MessageForm(forms.Form):
-#    message = forms.CharField(label=u'数字')
-#
-#    def clean_message(self):
-##        print str(dir(self))
-#        print str(self.fields)
-#        print "**** clean_message ...",str(self.cleaned_data )
-#        _c_message = self.cleaned_data['message']
-#        if re.match("^\d+$",_c_message) == None:
-#            raise forms.ValidationError(u'数字を入力してください')
-#        else:
-#            return _c_message
-#
-#    def is_valid(self):
-#        valid = super(MessageForm,self).is_valid()
-##        print "**** is_valid....",valid,dir(self)
-#        print "**** is_valid....",valid,str(self.data)
-#        return valid
-        
-
-#class MessageFormPreview(FormPreview):
-#    preview_template = 'djcube/signup_preview.html'
-#    form_template = 'djcube/signup.html'
-#    reedit_action= [u'ReEdit',]
-#
-#    def post_post(self, request):
-#        "Validates the POST data. If valid, calls done(). Else, redisplays form."
-#        f = self.form(request.POST, auto_id=AUTO_ID)
-#        reedit = False 
-#        if request.POST.has_key('action') and request.POST['action'] in self.reedit_action: 
-#            print "reedit....",str(dir(self.form))
-#            reedit = True
-#        
-#        if f.is_valid() and reedit == False:
-#            if self.security_hash(request, f) != request.POST.get(self.unused_name('hash')):
-#                return self.failed_hash(request) # Security hash failed.
-#            return self.done(request, f.cleaned_data)
-#        else:
-#            return render_to_response(self.form_template,
-#                {'form': f, 'stage_field': self.unused_name('stage'), 'state': self.state},
-#                context_instance=RequestContext(request))
-#
-#    def done(self, request, cleaned_data):
-#        print "done....."
-#        # Do something with the cleaned_data, then redirect
-#        # to a "success" page.
-#        return HttpResponseRedirect('/')
-
-#class MessageFormPreview(EditableFormPreview):
-#    preview_template = 'djcube/signup_preview.html'
-#    form_template = 'djcube/signup.html'
-#    reedit_action= [u'ReEdit',]
-#
-#
-#    def done(self, request, cleaned_data):
-#        print "done....."
-#        # Do something with the cleaned_data, then redirect
-#        # to a "success" page.
-#        return HttpResponseRedirect('/')
-

djcube/templates/base.html

     #formtools_tel02 { width:50px;}
     #formtools_tel03 { width:50px;}
     input:focus { border: 1px solid #974343; background-color: #fee8eb;}
+    .error { color:blue  ; }
 </style>
 
 <body>

djcube/templates/djcube/signup.html

 
 <form action="" method="post">
 姓 {{ form.name01 }} 名 {{ form.name02 }}               <br/>
-セイ {{ form.kana01 }} メイ {{ form.kana02 }}           <br/>
+セイ {{ form.kana01 }} メイ {{ form.kana02 }}  {{ form.kana01.errors}}  {{form.kana02.errors}}         <br/>
 住所 郵便 {{ form.zip01 }} - {{ form.zip02 }} 都道府県 {{ form.pref }} <br/> 
 市区町村 {{ form.addr01 }} 通り/建物 {{ form.addr02 }} <br/>
 <br>
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.