class SetPasswordForm(forms.Form): """ A form that lets a user change set his/her password without entering the old password """ error_messages = { 'password_mismatch': _("The two password fields didn't match."), } new_password1 = forms.CharField(label=_("New password"), widget=forms.PasswordInput) new_password2 = forms.CharField(label=_("New password confirmation"), widget=forms.PasswordInput) def __init__(self, user, *args, **kwargs): self.user = user super(SetPasswordForm, self).__init__(*args, **kwargs) def clean_new_password2(self): password1 = self.cleaned_data.get('new_password1') password2 = self.cleaned_data.get('new_password2') if password1 and password2: if password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch']) return password2 def save(self, commit=True): self.user.set_password(self.cleaned_data['new_password1']) if commit: self.user.save() return self.user
class AdminPasswordChangeForm(forms.Form): """ A form used to change the password of a user in the admin interface. """ error_messages = { 'password_mismatch': _("The two password fields didn't match."), } password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput) password2 = forms.CharField(label=_("Password (again)"), widget=forms.PasswordInput) def __init__(self, user, *args, **kwargs): self.user = user super(AdminPasswordChangeForm, self).__init__(*args, **kwargs) def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2: if password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch']) return password2 def save(self, commit=True): """ Saves the new password. """ self.user.set_password(self.cleaned_data["password1"]) if commit: self.user.save() return self.user
class AuthenticationForm(forms.Form): """ Base class for authenticating users. Extend this to get a form that accepts username/password logins. """ username = forms.CharField(label=_("Username"), max_length=30) password = forms.CharField(label=_("Password"), widget=forms.PasswordInput) error_messages = { 'invalid_login': _("Please enter a correct username and password. " "Note that both fields are case-sensitive."), 'no_cookies': _("Your Web browser doesn't appear to have cookies " "enabled. Cookies are required for logging in."), 'inactive': _("This account is inactive."), } def __init__(self, request=None, *args, **kwargs): """ If request is passed in, the form will validate that cookies are enabled. Note that the request (a HttpRequest object) must have set a cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before running this validation. """ self.request = request self.user_cache = None super(AuthenticationForm, self).__init__(*args, **kwargs) def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and password: self.user_cache = authenticate(username=username, password=password) if self.user_cache is None: raise forms.ValidationError( self.error_messages['invalid_login']) elif not self.user_cache.is_active: raise forms.ValidationError(self.error_messages['inactive']) self.check_for_test_cookie() return self.cleaned_data def check_for_test_cookie(self): if self.request and not self.request.session.test_cookie_worked(): raise forms.ValidationError(self.error_messages['no_cookies']) def get_user_id(self): if self.user_cache: return self.user_cache.id return None def get_user(self): return self.user_cache
class UserCreationForm(forms.ModelForm): """ A form that creates a user, with no privileges, from the given username and password. """ error_messages = { 'duplicate_username': _("A user with that username already exists."), 'password_mismatch': _("The two password fields didn't match."), } username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^[\w.@+-]+$', help_text = _("Required. 30 characters or fewer. Letters, digits and " "@/./+/-/_ only."), error_messages = { 'invalid': _("This value may contain only letters, numbers and " "@/./+/-/_ characters.")}) password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput) password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput, help_text = _("Enter the same password as above, for verification.")) class Meta: model = User fields = ("username",) def clean_username(self): # Since User.username is unique, this check is redundant, # but it sets a nicer error message than the ORM. See #13147. username = self.cleaned_data["username"] try: User.objects.get(username=username) except User.DoesNotExist: return username raise forms.ValidationError(self.error_messages['duplicate_username']) def clean_password2(self): password1 = self.cleaned_data.get("password1", "") password2 = self.cleaned_data["password2"] if password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch']) return password2 def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user
class CommentForm(CommentDetailsForm): honeypot = forms.CharField(required=False, label=_('If you enter anything in this field '\ 'your comment will be treated as spam')) def clean_honeypot(self): """Check that nothing's been entered into the honeypot.""" value = self.cleaned_data["honeypot"] if value: raise forms.ValidationError(self.fields["honeypot"].label) return value
def __init__(self, user, *args, **kwargs): super(HgRepositoryForm, self).__init__(*args, **kwargs) if user.is_authenticated() and self.data['display'] != 'all': self.fields['display'] = forms.CharField( max_length=11, required=False, widget=forms.Select(choices=self.DISPLAY_CHOICES)) for field in self.fields: if field == 'search': self.fields[field].widget.attrs[ 'style'] = "float: left; width: 30em;" else: self.fields[field].widget.attrs['style'] = "float: left;"
class PasswordChangeForm(SetPasswordForm): """ A form that lets a user change his/her password by entering their old password. """ error_messages = dict(SetPasswordForm.error_messages, **{ 'password_incorrect': _("Your old password was entered incorrectly. " "Please enter it again."), }) old_password = forms.CharField(label=_("Old password"), widget=forms.PasswordInput) def clean_old_password(self): """ Validates that the old_password field is correct. """ old_password = self.cleaned_data["old_password"] if not self.user.check_password(old_password): raise forms.ValidationError( self.error_messages['password_incorrect']) return old_password
class HgRepositoryForm(forms.Form): """ This form allows to search in the repositories """ DISPLAY_CHOICES = (('only_member', 'Only repositories I contribute'), ('only_owner', 'Only repositories I own')) search = forms.CharField(max_length=200, required=False) def __init__(self, user, *args, **kwargs): super(HgRepositoryForm, self).__init__(*args, **kwargs) if user.is_authenticated() and self.data['display'] != 'all': self.fields['display'] = forms.CharField( max_length=11, required=False, widget=forms.Select(choices=self.DISPLAY_CHOICES)) for field in self.fields: if field == 'search': self.fields[field].widget.attrs[ 'style'] = "float: left; width: 30em;" else: self.fields[field].widget.attrs['style'] = "float: left;" def clean_display(self): data = self.data['display'] return data def clean_search(self): data = self.data['search'] return data def is_valid(self): return True def as_a(self): "Returns this form rendered as HTML <tr>s -- excluding the <table></table>." return self._html_output(u'%(field)s%(help_text)s%(errors)s', u'%s', ' ', u'<br />%s', True)
class WizardPageTwoAlternativeForm(forms.Form): field = forms.CharField()
class HashTestBlankForm(forms.Form): name = forms.CharField(required=False) bio = forms.CharField(required=False)
class HashTestForm(forms.Form): name = forms.CharField() bio = forms.CharField()
class TestForm(forms.Form): field1 = forms.CharField() field1_ = forms.CharField() bool1 = forms.BooleanField(required=False)
class Page3(forms.Form): random_crap = forms.CharField(max_length=100)
class Page2(forms.Form): address1 = forms.CharField(max_length=100) address2 = forms.CharField(max_length=100)
class Page1(forms.Form): name = forms.CharField(max_length=100) user = forms.ModelChoiceField(queryset=User.objects.all()) thirsty = forms.NullBooleanField()
class CommentDetailsForm(CommentSecurityForm): """ Handles the specific details of the comment (name, comment, etc.). """ name = forms.CharField(label=_("Name"), max_length=50) email = forms.EmailField(label=_("Email address")) url = forms.URLField(label=_("URL"), required=False) comment = forms.CharField(label=_('Comment'), widget=forms.Textarea, max_length=COMMENT_MAX_LENGTH) def get_comment_object(self): """ Return a new (unsaved) comment object based on the information in this form. Assumes that the form is already validated and will throw a ValueError if not. Does not set any of the fields that would come from a Request object (i.e. ``user`` or ``ip_address``). """ if not self.is_valid(): raise ValueError( "get_comment_object may only be called on valid forms") CommentModel = self.get_comment_model() new = CommentModel(**self.get_comment_create_data()) new = self.check_for_duplicate_comment(new) return new def get_comment_model(self): """ Get the comment model to create with this form. Subclasses in custom comment apps should override this, get_comment_create_data, and perhaps check_for_duplicate_comment to provide custom comment models. """ return Comment def get_comment_create_data(self): """ Returns the dict of data to be used to create a comment. Subclasses in custom comment apps that override get_comment_model can override this method to add extra fields onto a custom comment model. """ return dict( content_type=ContentType.objects.get_for_model(self.target_object), object_pk=force_unicode(self.target_object._get_pk_val()), user_name=self.cleaned_data["name"], user_email=self.cleaned_data["email"], user_url=self.cleaned_data["url"], comment=self.cleaned_data["comment"], submit_date=timezone.now(), site_id=settings.SITE_ID, is_public=True, is_removed=False, ) def check_for_duplicate_comment(self, new): """ Check that a submitted comment isn't a duplicate. This might be caused by someone posting a comment twice. If it is a dup, silently return the *previous* comment. """ possible_duplicates = self.get_comment_model()._default_manager.using( self.target_object._state.db).filter( content_type=new.content_type, object_pk=new.object_pk, user_name=new.user_name, user_email=new.user_email, user_url=new.user_url, ) for old in possible_duplicates: if old.submit_date.date() == new.submit_date.date( ) and old.comment == new.comment: return old return new def clean_comment(self): """ If COMMENTS_ALLOW_PROFANITIES is False, check that the comment doesn't contain anything in PROFANITIES_LIST. """ comment = self.cleaned_data["comment"] if settings.COMMENTS_ALLOW_PROFANITIES == False: bad_words = [ w for w in settings.PROFANITIES_LIST if w in comment.lower() ] if bad_words: raise forms.ValidationError( ungettext( "Watch your mouth! The word %s is not allowed here.", "Watch your mouth! The words %s are not allowed here.", len(bad_words)) % get_text_list([ '"%s%s%s"' % (i[0], '-' * (len(i) - 2), i[-1]) for i in bad_words ], ugettext('and'))) return comment
class CommentSecurityForm(forms.Form): """ Handles the security aspects (anti-spoofing) for comment forms. """ content_type = forms.CharField(widget=forms.HiddenInput) object_pk = forms.CharField(widget=forms.HiddenInput) timestamp = forms.IntegerField(widget=forms.HiddenInput) security_hash = forms.CharField(min_length=40, max_length=40, widget=forms.HiddenInput) def __init__(self, target_object, data=None, initial=None): self.target_object = target_object if initial is None: initial = {} initial.update(self.generate_security_data()) super(CommentSecurityForm, self).__init__(data=data, initial=initial) def security_errors(self): """Return just those errors associated with security""" errors = ErrorDict() for f in ["honeypot", "timestamp", "security_hash"]: if f in self.errors: errors[f] = self.errors[f] return errors def clean_security_hash(self): """Check the security hash.""" security_hash_dict = { 'content_type': self.data.get("content_type", ""), 'object_pk': self.data.get("object_pk", ""), 'timestamp': self.data.get("timestamp", ""), } expected_hash = self.generate_security_hash(**security_hash_dict) actual_hash = self.cleaned_data["security_hash"] if not constant_time_compare(expected_hash, actual_hash): raise forms.ValidationError("Security hash check failed.") return actual_hash def clean_timestamp(self): """Make sure the timestamp isn't too far (> 2 hours) in the past.""" ts = self.cleaned_data["timestamp"] if time.time() - ts > (2 * 60 * 60): raise forms.ValidationError("Timestamp check failed") return ts def generate_security_data(self): """Generate a dict of security data for "initial" data.""" timestamp = int(time.time()) security_dict = { 'content_type': str(self.target_object._meta), 'object_pk': str(self.target_object._get_pk_val()), 'timestamp': str(timestamp), 'security_hash': self.initial_security_hash(timestamp), } return security_dict def initial_security_hash(self, timestamp): """ Generate the initial security hash from self.content_object and a (unix) timestamp. """ initial_security_dict = { 'content_type': str(self.target_object._meta), 'object_pk': str(self.target_object._get_pk_val()), 'timestamp': str(timestamp), } return self.generate_security_hash(**initial_security_dict) def generate_security_hash(self, content_type, object_pk, timestamp): """ Generate a HMAC security hash from the provided info. """ info = (content_type, object_pk, timestamp) key_salt = "my_django.contrib.forms.CommentSecurityForm" value = "-".join(info) return salted_hmac(key_salt, value).hexdigest()
class Page1(forms.Form): name = forms.CharField(max_length=100) thirsty = forms.NullBooleanField()
class Step2(forms.Form): name = forms.CharField()
class Step3(forms.Form): data = forms.CharField()
class WizardPageThreeForm(forms.Form): field = forms.CharField()
class ManagementForm(forms.Form): """ ``ManagementForm`` is used to keep track of the current wizard step. """ current_step = forms.CharField(widget=forms.HiddenInput)