This repository has been archived on 2023-02-21. You can view files and clone it, but cannot push or open issues or pull requests.
auf-auf-django-secretquestions/secretquestions/forms.py

87 lines
2.4 KiB
Python

# -*- coding: utf-8 -*-
from django.conf import settings
from django import forms
from django.forms.models import modelformset_factory, ModelForm
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from .models import Answer, crypt_answer, check_answer
MAX_SECRET_QUESTIONS = getattr(settings, 'MAX_SECRET_QUESTIONS', 3)
class AnswerForm(ModelForm):
class Meta:
model = Answer
def __init__(self, *args, **kwargs):
if 'instance' in kwargs:
kwargs['instance'].secret = ""
super(AnswerForm, self).__init__(*args, **kwargs)
def clean_secret(self):
data = self.cleaned_data['secret']
return crypt_answer(data)
_FreeAnswerFormSet = modelformset_factory(Answer, form=AnswerForm,
fields=("question", "secret"),
extra=MAX_SECRET_QUESTIONS,
max_num=MAX_SECRET_QUESTIONS,
can_delete=False)
class AnswerFormSet(_FreeAnswerFormSet):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super(AnswerFormSet, self).__init__(*args, **kwargs)
def save_all(self):
instances = self.save(commit=False)
for instance in instances:
instance.user = self.user
instance.save()
def clean(self):
questions = []
for i in range(0, self.total_form_count()):
form = self.forms[i]
try:
question = form.cleaned_data.get('question')
except:
question = None
if question is None:
raise forms.ValidationError(
_("All questions have to be selected."))
if question in questions:
raise forms.ValidationError(
_("Each question has to be different."))
questions.append(question)
return super(AnswerFormSet, self).clean()
class UsernameForm(forms.Form):
username = forms.CharField()
def clean_username(self):
data = self.cleaned_data['username']
try:
return User.objects.get(username=data)
except User.DoesNotExist:
raise forms.ValidationError(_("Username not found"))
class QuestionForm(forms.Form):
raw_answer = forms.CharField()
def clean_raw_answer(self):
data = self.cleaned_data['raw_answer']
if not check_answer(data, self.answer.secret):
raise forms.ValidationError(_("This answer is incorrect."))