class RegistrationForm(forms.Form): username = forms.CharField(label='Username', max_length=30) email = forms.EmailField(label='Email') password1 = forms.CharField(label='Password', widget=forms.PasswordInput()) password2 = forms.CharField(label='Password (Again)', widget=forms.PasswordInput()) def clean_password2(self): if 'password1' in self.clean_data: password1 = self.clean_data['password1'] password2 = self.clean_data['password2'] if password1 == password2: return password2 raise forms.ValidationError('Passwords do not match.') def clean_username(self): username = self.clean_data['username'] if not re.search(r'^\w+$', username): raise forms.ValidationError( 'Username can only containalphanumeric characters and the underscore.' ) try: User.objects.get(username=username) except ObjectDoesNotExist: return username raise forms.ValidationError('Username is already taken.')
class SignUpForm(forms.Form): which_form = forms.CharField(widget=forms.HiddenInput, initial="signup") signup_email = forms.EmailField(label="Email") signup_first_name = forms.CharField(label="First Name") signup_last_name = forms.CharField(label="Last Name") signup_password = forms.CharField(widget=forms.PasswordInput,label="Password") signup_password_confirm = forms.CharField(widget=forms.PasswordInput,label="Verify Password")
class PasswordResetForm(forms.Form): """ Checks for valid username or email address """ # form inputs email = forms.EmailField()
def formfield(self, **kwargs): defaults = { 'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text } defaults.update(kwargs) return forms.EmailField(**defaults)
class ApplianceForm(forms.Form): url = forms.URLField() email = forms.EmailField() appliance_type = forms.ChoiceField(choices = [('', 'Unknown'), ('EC2', 'Amazon EC2'), ('VMX', 'VMware'), ('Devel', 'Development')])
class SignupForm(LoginForm): """ Creates signup form instance with custom validation """ # form inputs email = forms.EmailField() password2 = forms.CharField(widget=PasswordInput) first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) where_heard = forms.CharField(max_length=100, required=False) def clean_password2(self): """ Validates that the two password inputs match. """ if self.cleaned_data.get('password', None) and self.cleaned_data.get('password2', None) and \ self.cleaned_data['password'] == self.cleaned_data['password2']: return self.cleaned_data['password2'] else: raise forms.ValidationError(u'The passwords did not match') def clean_username(self): """ Validates that username is not in use """ username = self.cleaned_data.get('username', None) if username: try: User.objects.get(username=username) raise forms.ValidationError( u'username already exists, please choose another') except User.DoesNotExist: return username def save(self): """ Overrides save method to commit user to database and set their profile and group information """ user = User.objects.create_user( username=self.cleaned_data['username'], email=self.cleaned_data['email'], \ password=self.cleaned_data['password']) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] # add user to 'users' group so we can easily deal with permissions group_user = Group.objects.get(name="users") user.groups.add(group_user) user.save() # add profile info user_profile = UserProfile( where_heard=self.cleaned_data['where_heard'], criteria_pref_type="simple", user=user) user_profile.save() return user
class ContactForm(forms.Form): """ Contact form """ # form inputs name = forms.CharField() email = forms.EmailField() message = forms.CharField(widget=Textarea)
class RegistrationForm(forms.Form): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) email = forms.EmailField() username = forms.RegexField( r"^[a-zA-Z0-9_\-\.]*$", max_length=30, error_message='Only A-Z, 0-9, "_", "-", and "." allowed.') password = forms.CharField(min_length=5, max_length=30) password2 = forms.CharField()
class EmailForm(forms.Form): FromName = forms.CharField(initial='MedCommons') FromEmail = forms.EmailField( \ initial = '*****@*****.**', help_text = "Emails to users are from this email address") IncomingEmailEnabled = forms.ChoiceField( choices=[('0', 'Disabled'), ('1', 'Enabled')], help_text="Enables incoming email of the form {mcid}@{domain name}")
class SKeyForm(forms.Form): skey = forms.CharField(label='S/Key', widget=forms.TextInput(attrs=dict(size=30))) email = forms.EmailField(widget=forms.TextInput(attrs=dict(size=42))) newpw = forms.CharField(label='New Password') def clean_skey(self): s = self.data['skey'] try: return skey.put(skey.get(s)) except KeyError: raise forms.ValidationError('Invalid S/Key data')
class CreateForm(forms.Form): username = forms.RegexField('^[a-zA-Z0-9_]*$', max_length=30) first_name = forms.CharField(max_length = 30, required = False) last_name = forms.CharField(max_length = 30, required = False) email = forms.EmailField() pw1 = forms.CharField(widget = forms.PasswordInput, label = 'Password') pw2 = forms.CharField(widget = forms.PasswordInput, label = 'Password (again)', required = False)
class UserForm(CreateForm): email = forms.EmailField(required=False) pw1 = forms.CharField(widget=forms.PasswordInput, label='Password', required=False) pw2 = forms.CharField(widget=forms.PasswordInput, label='Password (again)', required=False) enable_simtrak = forms.BooleanField(required=False, label='Enable Simtrak') enable_dod = forms.BooleanField(required=False, label='DICOM on Demand User') def clean_pw2(self): if self.data['pw1'] != self.data['pw2']: raise forms.ValidationError('Passwords must match') return self.data['pw2']
class NewsletterForm(forms.Form): full_name = forms.CharField(label=_('Full Name'), max_length=100, required=False) email = forms.EmailField(label=_('Email address'), max_length=50, required=True) subscribed = OptionalBoolean(label=_('Subscribe'), required=False, initial=True) def get_contact(self): data = self.cleaned_data email = data['email'] full_name = data['full_name'] return get_contact_or_fake(full_name, email)
class SignupForm(forms.Form): username = forms.CharField(label="Username", max_length=30, widget=forms.TextInput()) password1 = forms.CharField(label="Password", widget=forms.PasswordInput()) password2 = forms.CharField(label="Password (again)", widget=forms.PasswordInput()) email = forms.EmailField(label="Email (optional)", required=False, widget=forms.TextInput()) def clean_username(self): if not alnum_re.search(self.cleaned_data["username"]): raise forms.ValidationError( u"Usernames can only contain letters, numbers and underscores." ) try: user = User.objects.get( username__exact=self.cleaned_data["username"]) except User.DoesNotExist: return self.cleaned_data["username"] raise forms.ValidationError( u"This username is already taken. Please choose another.") def clean(self): if "password1" in self.cleaned_data and "password2" in self.cleaned_data: if self.cleaned_data["password1"] != self.cleaned_data["password2"]: raise forms.ValidationError( u"You must type the same password each time.") return self.cleaned_data def save(self): print self.cleaned_data username = self.cleaned_data["username"] email = self.cleaned_data["email"] password = self.cleaned_data["password1"] new_user = User.objects.create_user(username, email, password) if email: self.user.message_set.create( message="Confirmation email sent to %s" % email) EmailAddress.objects.add_email(new_user, email) return username, password # required for authenticate()
class RegistrationForm(forms.Form): """The basic account registration form.""" email = forms.EmailField(label=_('Email address'), max_length=30, required=True) password2 = forms.CharField(label=_('Password (again)'), max_length=30, widget=forms.PasswordInput(), required=True) password = forms.CharField(label=_('Password'), max_length=30, widget=forms.PasswordInput(), required=True) first_name = forms.CharField(label=_('First name'), max_length=30, required=True) last_name = forms.CharField(label=_('Last name'), max_length=30, required=True) newsletter = forms.BooleanField(label=_('Newsletter'), widget=forms.CheckboxInput(), required=False) def clean_password(self): """Enforce that password and password2 are the same.""" p1 = self.cleaned_data.get('password') p2 = self.cleaned_data.get('password2') if not (p1 and p2 and p1 == p2): raise forms.ValidationError( ugettext("The two passwords do not match.")) # note, here is where we'd put some kind of custom validator to enforce "hard" passwords. return p1 def clean_email(self): """Prevent account hijacking by disallowing duplicate emails.""" email = self.cleaned_data.get('email', None) if email and User.objects.filter(email=email).count() > 0: raise forms.ValidationError( ugettext("That email address is already in use.")) return email
class FeedbackForm(forms.Form): name = forms.CharField(required=False) email = forms.EmailField(required=False) comment = forms.CharField(required=True) referrer = forms.CharField() token = forms.CharField() def clean_token(self): if FeedbackToken.get(self.cleaned_data['token']): return self.cleaned_data['token'] else: # We should only get here in the event of: # 1. A spam bot # 2. A human user that left the form open for a very long time # # In the event of (2), let's give them a second chance by # generating a new token. We're hoping spam bots aren't # smart enough yet to parse the new form. raise forms.ValidationError( "Your session expired. Please try again.")
class AddEmailForm(forms.Form): def __init__(self, data=None, user=None): super(AddEmailForm, self).__init__(data=data) self.user = user email = forms.EmailField(label="Email", required=True, widget=forms.TextInput()) def clean_email(self): try: EmailAddress.objects.get(user=self.user, email=self.cleaned_data["email"]) except EmailAddress.DoesNotExist: return self.cleaned_data["email"] raise forms.ValidationError( u"This email address already associated with this account.") def save(self): self.user.message_set.create(message="Confirmation email sent to %s" % self.cleaned_data["email"]) return EmailAddress.objects.add_email(self.user, self.cleaned_data["email"])
class ContactForm(forms.Form): topic = forms.ChoiceFiled(choice=TOPIC_CHOICES) message = forms.CharFiled() sender = forms.EmailField(required=False)
class ChangeProfileForm(forms.Form): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) email = forms.EmailField()
class LoginForm(forms.Form): which_form = forms.CharField(widget=forms.HiddenInput, initial="login") login_email = forms.EmailField(label="Email") login_password = forms.CharField(widget=forms.PasswordInput, label="Password", error_messages={'required': 'Please enter your password'})
class NewCommentForm(forms.Form): article_url = forms.URLField(required=True, widget=forms.HiddenInput) article_title = forms.CharField(required=False, widget=forms.HiddenInput) author_name = forms.CharField(required=True, label="Name") author_email = forms.EmailField(required=True, label="Email") author_url = forms.URLField(required=False, label="URL") author_ip = forms.CharField(required=False) comment = forms.CharField(required=True, widget=forms.Textarea(attrs={ 'cols': 30, 'rows': 3 })) def save(self): data = self.clean_data article_url = data.get('article_url') article_title = data.get('article_title') or data.get('article_url') article = models.Article.get_or_insert(article_url, url=article_url, title=article_title) if article.title != article_title: article.title = article_title article.put() author_email = data.get('author_email') author_name = data.get('author_name') author_url = data.get('author_url') author_ip = data.get('author_ip') author_key = (author_email or '') + author_name author = models.Author.get_or_insert(author_key, name=author_name) has_changes = False if author.url != author_url and author_url: author.url = author_url has_changes = True if author_email and author_email != author.email: author.email = author_email has_changes = True if has_changes: author.put() comment = models.Comment(parent=article, comment=data.get('comment'), author=author, article=article, author_ip=author_ip) comment.put() params = urllib.urlencode({ 'article_url': article_url, 'comment_id': comment.key().id() }) taskqueue.add(url="/api/notify/?" + params, method="GET") self._author = author self._article = article self._comment = comment return comment @property def output(self): return { 'article': { 'url': self._article.url, 'title': self._article.title, }, 'author': { 'email': self._author.email, 'name': self._author.name, 'url': self._author.url, }, 'comment': self._comment.comment, }
class ContactForm(forms.Form): name = forms.CharField(label=_("Name"), max_length=100) sender = forms.EmailField(label=_("Email address")) subject = forms.CharField(label=_("Subject")) inquiry = forms.ChoiceField(label=_("Inquiry"), choices=email_choices) contents = forms.CharField(label=_("Contents"), widget=widgets.Textarea(attrs = {'cols': 40, 'rows': 5}))
class InviteForm(forms.Form): email = forms.EmailField(label=_('Email'))
class UserForm(newforms.Form): username = newforms.CharField(max_length=50) first_name = newforms.CharField() last_name = newforms.CharField() email = newforms.EmailField() password = newforms.CharField( widget=newforms.PasswordInput(render_value=False), required=False) password_confirm = newforms.CharField( widget=newforms.PasswordInput(render_value=False), required=False) is_superuser = newforms.BooleanField(required=False) def __init__(self, *args, **kwargs): debugOutput("Creating") # Pre-load with user details if there is a user. if "user" in kwargs and kwargs["user"]: user = kwargs["user"] initial = user self.mode = "edit" # TODO: Load the roles of this user. else: initial = None user = None self.mode = "create" if "user" in kwargs: del kwargs["user"] super(self.__class__, self).__init__(initial=initial, *args, **kwargs) # Setup the roles field. choices = [(role, role) for role in wikidbase.core.security.getRoles()] userRoles = user and wikidbase.core.security.getUserRoles( user["username"]) or [] self.fields["roles"] = newforms.MultipleChoiceField( initial=userRoles, widget=newforms.CheckboxSelectMultiple, choices=choices, required=False) def clean(self): if 'password' in self.clean_data and 'password_confirm' in self.clean_data: if self.clean_data['password'] != self.clean_data[ 'password_confirm']: raise newforms.ValidationError(u'The passwords do not match.') return self.clean_data def save(self): debugOutput("Saving") # Try to get an existing user user = wikidbase.core.security.getUser( self.clean_data["username"]) or {} for field in self.clean_data: user[field] = self.clean_data[field] # Update roles. wikidbase.core.security.setUserRoles(self.clean_data["username"], self.clean_data["roles"]) # Save the user. wikidbase.core.security.saveUser(user)
class ClaimForm(forms.Form): email = forms.EmailField(required=False) password = forms.CharField()
class SubscriberForm(forms.Form): email = forms.EmailField(label='Email')
class LoginForm(forms.Form): email = forms.EmailField(max_length=100) password = forms.CharField(max_length=100, widget=forms.PasswordInput)
class FeedbackForm(forms.Form): message = forms.CharField(max_length=500, widget=forms.Textarea()) email = forms.EmailField(required=False, max_length=100, label='Your email (optional)')
class ContactInfoForm(forms.Form): email = forms.EmailField(max_length=30) first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) phone = forms.CharField(max_length=30) street1 = forms.CharField(max_length=30) street2 = forms.CharField(max_length=30, required=False) city = forms.CharField(max_length=30) state = forms.CharField(max_length=30, required=False) country = forms.CharField(max_length=30, required=False) postal_code = forms.CharField(max_length=10) copy_address = forms.BooleanField(required=False) ship_street1 = forms.CharField(max_length=30, required=False) ship_street2 = forms.CharField(max_length=30, required=False) ship_city = forms.CharField(max_length=30, required=False) ship_state = forms.CharField(max_length=30, required=False) ship_postal_code = forms.CharField(max_length=10, required=False) def __init__(self, countries, areas, *args, **kwargs): super(ContactInfoForm, self).__init__(*args, **kwargs) if areas is not None and countries is None: self.fields['state'] = forms.ChoiceField(choices=areas, initial=selection) self.fields['ship_state'] = forms.ChoiceField(choices=areas, initial=selection, required=False) if countries is not None: self.fields['country'] = forms.ChoiceField(choices=countries) shop_config = Config.get_shop_config() self._local_only = shop_config.in_country_only country = shop_config.sales_country if not country: self._default_country = 'US' else: self._default_country = country.iso2_code def clean_state(self): if self._local_only: country_iso2 = self._default_country else: country_iso2 = self.data['country'] data = self.cleaned_data['state'] country = Country.objects.get(iso2_code=country_iso2) if country.adminarea_set.count() > 0: if not data or data == selection: raise forms.ValidationError( self._local_only and _('This field is required.') \ or _('State is required for your country.')) return data def clean_ship_state(self): if self.cleaned_data['copy_address']: if 'state' in self.cleaned_data: self.cleaned_data['ship_state'] = self.cleaned_data['state'] return self.cleaned_data['ship_state'] if self._local_only: country_iso2 = self._default_country else: country_iso2 = self.data['country'] data = self.cleaned_data['ship_state'] country = Country.objects.get(iso2_code=country_iso2) if country.adminarea_set.count() > 0: if not data or data == selection: raise forms.ValidationError( self._local_only and _('This field is required.') \ or _('State is required for your country.')) return data def clean_country(self): if self._local_only: return self._default_country return self.cleaned_data['country'] def ship_charfield_clean(self, field_name): if self.cleaned_data['copy_address']: if field_name in self.cleaned_data: self.cleaned_data['ship_' + field_name] = self.cleaned_data[field_name] return self.cleaned_data['ship_' + field_name] field = forms.CharField(max_length=30) return field.clean(self.cleaned_data['ship_' + field_name]) def clean_ship_street1(self): return self.ship_charfield_clean('street1') def clean_ship_street2(self): if self.cleaned_data['copy_address']: if 'street2' in self.cleaned_data: self.cleaned_data['ship_street2'] = self.cleaned_data['street2'] return self.cleaned_data['ship_street2'] def clean_ship_city(self): return self.ship_charfield_clean('city') def clean_ship_postal_code(self): return self.ship_charfield_clean('postal_code') def save(self, contact=None, update_newsletter=True): """Save the contact info into the database. Checks to see if contact exists. If not, creates a contact and copies in the address and phone number.""" if not contact: customer = Contact() else: customer = contact data = self.cleaned_data for field in customer.__dict__.keys(): try: setattr(customer, field, data[field]) except KeyError: pass if update_newsletter and config_get_group('NEWSLETTER'): from satchmo.newsletter import update_subscription if 'newsletter' not in data: subscribed = False else: subscribed = data['newsletter'] update_subscription(contact, subscribed) if not customer.role: customer.role = "Customer" customer.save() # we need to make sure we don't blindly add new addresses # this isn't ideal, but until we have a way to manage addresses # this will force just the two addresses, shipping and billing # TODO: add address management like Amazon. bill_address = customer.billing_address if not bill_address: bill_address = AddressBook(contact=customer) address_keys = bill_address.__dict__.keys() for field in address_keys: try: setattr(bill_address, field, data[field]) except KeyError: pass bill_address.is_default_billing = True copy_address = data['copy_address'] ship_address = customer.shipping_address if copy_address: # make sure we don't have any other default shipping address if ship_address and ship_address.id != bill_address.id: ship_address.delete() bill_address.is_default_shipping = True bill_address.save() if not copy_address: if not ship_address or ship_address.id == bill_address.id: ship_address = AddressBook() for field in address_keys: try: setattr(ship_address, field, data['ship_' + field]) except KeyError: pass ship_address.is_default_shipping = True ship_address.is_default_billing = False ship_address.contact = customer ship_address.country = bill_address.country ship_address.save() if not customer.primary_phone: phone = PhoneNumber() phone.primary = True else: phone = customer.primary_phone phone.phone = data['phone'] phone.contact = customer phone.save() return customer.id
class SignupForm(forms.Form, SavesPayment): def __init__(self, requires_payment, *args, **kwargs): self.requires_payment = requires_payment forms.Form.__init__(self, *args, **kwargs) if not requires_payment: del self.fields['card_number'] del self.fields['card_expiration'] first_name = forms.CharField( label="First name", min_length=2, max_length=30, ) last_name = forms.CharField( label="Last name", min_length=2, max_length=30, ) email = forms.EmailField(label="Email", ) username = forms.CharField( label="Username", help_text="You'll use this to log in", min_length=4, max_length=30, ) password = forms.CharField(label="Password", min_length=6, max_length=20, widget=forms.PasswordInput()) password2 = forms.CharField( label="Password again", help_text="Confirm your password by entering it again", min_length=6, max_length=20, widget=forms.PasswordInput()) group = forms.CharField( label="Company / Organization", min_length=2, max_length=30, ) timezone = forms.ChoiceField( label="Time zone", choices=settings.ACCOUNT_TIME_ZONES, initial=settings.ACCOUNT_DEFAULT_TIME_ZONE, ) # Domain must come BEFORE subdomain. Cleaning order is important. domain = forms.ChoiceField(choices=settings.ACCOUNT_DOMAINS) subdomain = forms.CharField( min_length=2, max_length=30, ) #card_type = forms.ChoiceField( #label = "Card type", #choices = enumerate(['Visa', 'Mastercard', 'AmericanExpress']), #required = False, #) card_number = forms.CharField( label="Card number", required=False, ) card_expiration = forms.DateField( label="Expiration", required=False, ) terms_of_service = forms.BooleanField( label="I agree to the Terms of Service, Refund, and Privacy policies") def clean_password2(self): if self.cleaned_data['password'] != self.cleaned_data['password2']: raise forms.ValidationError( "The two passwords didn't match. Please try again.") return self.cleaned_data['password2'] def clean_subdomain(self): if not self.cleaned_data['subdomain'].isalnum(): raise forms.ValidationError( "Your subdomain can only include letters and numbers.") try: Account.objects.get( subdomain=self.cleaned_data['subdomain'], domain=self.data['domain'], ) raise forms.ValidationError( "The domain %s.%s has already been taken" % (self.cleaned_data['subdomain'], self.cleaned_data['domain'])) except Account.DoesNotExist: pass return self.cleaned_data['subdomain'] def clean_terms_of_service(self): if not self.cleaned_data['terms_of_service']: raise forms.ValidationError( "Sorry, but we can't create your account unless you accept the terms of service." ) def save_account(self, level): account = Account( domain=self.cleaned_data['domain'], subdomain=self.cleaned_data['subdomain'], timezone=self.cleaned_data['timezone'], name=self.cleaned_data['group'], subscription_level_id=level, ) if not account.validate(): account.save() return account else: raise ValueError def save_person(self, account): person = Person( account=account, username=self.cleaned_data['username'], first_name=self.cleaned_data['first_name'], last_name=self.cleaned_data['last_name'], email=self.cleaned_data['email'], ) person.set_password(self.cleaned_data['password']) if not person.validate(): person.save() return person else: raise ValueError