# 1.settings.py INSTALLED_APPS = ( 'captcha', ) # django_simple_captcha 驗證碼配置 # 格式 CAPTCHA_OUTPUT_FORMAT = u'%(text_field)s %(hidden_field)s %(image)s' # 噪點樣式 CAPTCHA_NOISE_FUNCTIONS = ('captcha.helpers.noise_null', # 沒有樣式 # 'captcha.helpers.noise_arcs', # 線 # 'captcha.helpers.noise_dots', # 點 ) # 圖片大小 CAPTCHA_IMAGE_SIZE = (100, 25) CAPTCHA_BACKGROUND_COLOR = '#ffffff' CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.random_char_challenge' # 圖片中的文字為隨機英文字母,如 mdsh # CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.math_challenge' # 圖片中的文字為數字表達式,如1+2=</span> CAPTCHA_LENGTH = 4 # 字符個數 CAPTCHA_TIMEOUT = 1 # 超時(minutes) # 2.forms.py from django import forms from maiziedu.models import UserProfile from captcha.fields import CaptchaField class RegisterForm(forms.Form): ''''' 注冊 ''' username = forms.EmailField(widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "請輸入郵箱賬號", "value": "", "required": "required",}), max_length=50,error_messages={"required": "用戶名不能為空",}) password = forms.CharField(widget=forms.PasswordInput(attrs={"class": "form-control", "placeholder": "請輸入密碼", "value": "", "required": "required",}), min_length=8, max_length=50,error_messages={"required": "密碼不能為空",}) # 驗證碼 captcha = CaptchaField() def clean(self): # 驗證碼 try: captcha_x = self.cleaned_data['captcha'] except Exception as e: print 'except: '+ str(e) raise forms.ValidationError(u"驗證碼有誤,請重新輸入") # 用戶名 try: username=self.cleaned_data['username'] except Exception as e: print 'except: '+ str(e) raise forms.ValidationError(u"注冊賬號需為郵箱格式") # 登錄驗證 is_email_exist = UserProfile.objects.filter(email=username).exists() is_username_exist = UserProfile.objects.filter(username=username).exists() if is_username_exist or is_email_exist: raise forms.ValidationError(u"該賬號已被注冊") # 密碼 try: password=self.cleaned_data['password'] except Exception as e: print 'except: '+ str(e) raise forms.ValidationError(u"請輸入至少8位密碼"); return self.cleaned_data # 3.views.py # 注冊 # 改為ajax post def register(request): if request.method == 'POST': # 驗證碼 print 'captcha_0: ' + request.POST.get('captcha_0') print 'captcha_1: ' + request.POST.get('captcha_1') try: reg_form = RegisterForm(request.POST) except Exception as e: print str(e) # 登錄失敗 返回錯誤提示 err = "注冊失敗,請重試" return result_response(request, err) if reg_form.is_valid(): print "register success" try: username = reg_form.cleaned_data['username'] password = reg_form.cleaned_data['password'] user = UserProfile.objects.create(username = username, email = username, password = make_password(password), is_active = True) user.save() user.backend = 'django.contrib.auth.backends.ModelBackend' # 指定默認的登錄驗證方式 # 驗證成功登錄 auth.login(request, user) return result_response(request, "") except Exception as e: print str(e) setFormTips(reg_form, "注冊失敗,請重試") else: print "register failed" if request.POST.get('captcha_1') == "": setFormTips(reg_form, "驗證碼不能為空") # 登錄失敗 返回錯誤提示 err = getFormTips(reg_form) return result_response(request, err) else: reg_form = RegisterForm() return render(request, 'index.html', locals()) # 4.index.html ①第一種 {{ reg_form.captcha }} # 這種方法對頁面的適應性不太好,如上面模板變量生成html如下: <input autocomplete="off" id="id_captcha_1" name="captcha_1" type="text"> <input id="id_captcha_0" name="captcha_0" type="hidden" value="e91228ab45df7338b59b64cb0eae1b60a48fd125"> <img src="/%2Fimage/e91228ab45df7338b59b64cb0eae1b60a48fd125/" alt="captcha" class="captcha"> ②第二種 # views.py from captcha.models import CaptchaStore from captcha.helpers import captcha_image_url hashkey = CaptchaStore.generate_key() imgage_url = captcha_image_url(hashkey) # index.html <input type="text" id="id_reg_captcha_1" name="captcha_1" class="form-control form-control-captcha fl" placeholder="請輸入驗證碼"><span class="v5-yzm fr"><a href="#" class="next-captcha"><img src="{{ imgage_url }}" class="captcha" alt="captcha">換一張</a></span> <input id="id_reg_captcha_0" name="captcha_0" type="hidden" value="{{ hashkey }}">
