def registration(request): cletters = random.choice(ascii_lowercase) + random.choice(ascii_lowercase) + random.choice(ascii_lowercase) + random.choice(ascii_lowercase) ckey = str(random.SystemRandom().randrange(0, 18446744073709551616L)) + str(time.time()) key_ = unicodedata.normalize('NFKD', ckey + unicode(cletters.upper())).encode('ascii', 'ignore') + unicodedata.normalize('NFKD', unicode(cletters)).encode('ascii', 'ignore') key = hashlib.sha1(key_).hexdigest() print key print cletters cptmod = Captcha() cptmod.hash = key cptmod.code = cletters cptmod.save() c = { 'key' : key, 'form': RegistrationForm, } return render(request, 'registration.html', c)
def render(self, name, value, attrs=None): captcha = Captcha() raw_html = u'<input type="text" name="%s" />' % name raw_html = u'%s \r\n %s' % ( raw_html, u'<img class="captcha" src="%s" />' % captcha.url) return mark_safe(raw_html)
def __init__(self, *args, **kwargs): super(CaptchaForm, self).__init__(*args, **kwargs) # The super.__init__ call does not actually set the data or initial # onto the fields/widgets, so we just need the captcha_id field and # widget to exist before self.get_captcha() is called self.fields['captcha_id'] = forms.IntegerField() self.fields['captcha_id'].widget = forms.HiddenInput() if not self.is_bound: # New form, new captcha c = Captcha(text=get_string()) c.save() # Ensure that the hidden field is properly populated self.initial['captcha_id'] = c.id else: c = self.get_captcha() self.fields['captcha'] = CaptchaField(label="Turing test", captcha=c)
def get_captcha(self): # Somewhat hacky, but best way I had to get the captcha id f = self.fields['captcha_id'] w = f.widget #value = w.value_from_datadict(self.data, None, self.add_prefix('captcha_id')) #make it work in 0.96, where value_from_datadict() have 2 arguments value = w.value_from_datadict(self.data, self.add_prefix('captcha_id')) captcha_id = f.clean(value) try: # Always clean expired captchas before getting one for validation Captcha.clean_expired() return Captcha.objects.get(pk=captcha_id) except Captcha.DoesNotExist: # The original captcha expired, make a new one for revalidation c = Captcha(id=captcha_id,text=get_string()) c.save() return c