class DistanceForm(forms.Form): ocean = forms.IntegerField(min_value=1, max_value=100, widget=forms.TextInput(attrs={ 'maxlength': 3, 'size': 3 })) group = forms.IntegerField(min_value=1, max_value=100, widget=forms.TextInput(attrs={ 'maxlength': 3, 'size': 3 })) isle_num = forms.IntegerField(min_value=1, max_value=25, widget=forms.TextInput(attrs={ 'maxlength': 2, 'size': 3 })) rulerless = forms.BooleanField(required=False, label="Rulerless", initial=True) weak = forms.BooleanField( required=False, label="Ruled by Weak Players (Really? Pick on the newbs?)") threshold = forms.IntegerField(required=False, min_value=0, initial=2500, label='...with a score threshold of')
def __init__(self, *args, **kwargs): products = kwargs.pop('products', None) super(ProductExportForm, self).__init__(*args, **kwargs) self.fields['format'] = forms.ChoiceField(label=_('export format'), choices=export_choices(), required=True) self.fields['include_images'] = forms.BooleanField( label=_('Include Images'), initial=True, required=False) if not products: products = Product.objects.all().order_by('slug') for product in products: subtypes = product.get_subtypes() expclasses = ('export', ) + subtypes extclasses = " ".join(expclasses) kw = { 'label': product.slug, 'help_text': product.name, 'initial': False, 'required': False, 'widget': forms.CheckboxInput(attrs={'class': extclasses}) } chk = forms.BooleanField(**kw) chk.slug = product.slug chk.product_id = product.id chk.subtypes = " ".join(subtypes) self.fields['export__%s' % product.slug] = chk
class RepositoryForm(forms.Form): location = forms.CharField( widget=forms.TextInput(attrs={'class': 'text-wide'}), ) enable_polling = forms.BooleanField( required=False, widget=forms.CheckboxInput(attrs={'class': 'checkbox'}), ) forward_pinger_mail = forms.BooleanField( required=False, widget=forms.CheckboxInput(attrs={'class': 'checkbox'}), ) poll_frequency = forms.IntegerField( widget=forms.TextInput(attrs={'class': 'text'}), ) revision_url = forms.CharField( required=False, widget=forms.TextInput(attrs={'class': 'text-wide'}), ) path_regexes = forms.CharField( required=False, widget=forms.Textarea, ) def clean_location(self): # On success, this will set up internal state in the # model but *not* set the location itself. That will # be done during apply(), so that it's included in # the changeset. location = self.cleaned_data['location'] # XXX - Bear hack: Unconditionally probe, so if we reactivated # the repository we don't pull all revisions since way back when. # Also makes sure the location is still valid. #if location != self.data.model.location: if location: # shouldn't be neccessary, required = True self.data.model.get_client().probe(location) return location def clean_revision_url(self): return self.cleaned_data.get('revision_url') or None def clean_path_regexes(self): # Remove extra whitespace and blank lines, then parse the resulting regexes. regexes = [] line_no = 1 for line in self.cleaned_data.get('path_regexes', '').split('\n'): line = line.strip() if line: try: re.compile(line, re.VERBOSE) except re.error, e: raise forms.ValidationError("Syntax error on line %d: %s" % (line_no, e)) regexes.append(line) line_no += 1 if regexes: return '\n'.join(regexes)
class DistanceForm(forms.Form): ocean = forms.IntegerField(min_value=1, max_value=100, widget=forms.TextInput(attrs={'maxlength':3, 'size':3} )) group = forms.IntegerField(min_value=1, max_value=100, widget=forms.TextInput(attrs={'maxlength':3, 'size':3} )) isle_num = forms.IntegerField(min_value=1, max_value=25, widget=forms.TextInput(attrs={'maxlength':2, 'size':3} )) rulerless = forms.BooleanField(required=False, label="Rulerless", initial=True) low_score = forms.BooleanField(required=False, label='...with a score less than') threshold = forms.IntegerField(required=False, min_value=0, initial=2500 ) weak_alliance = forms.BooleanField(required=False, label='...in an alliance with a score less than') alliance_threshold = forms.IntegerField(required=False, min_value=0, initial=2500) low_island_count = forms.BooleanField(required=False, label='...with an island count less than') max_num_islands = forms.IntegerField(required=False, min_value=0, initial=6)
class ProjectForm(forms.Form): use_repository = forms.BooleanField( required=False, widget=forms.CheckboxInput(attrs={'class': 'checkbox'}), ) def apply(self, cset, request, repos): use_repository = bool(self.cleaned_data.get('use_repository')) if cset.asset.repos and cset.asset.repos.is_active and not use_repository: # Deactivate repository cset.set_field('repos.is_active', False) elif use_repository: # Activate repository, using either the asset's existing # repository or a temporary repository we created before # we knew it would definitely be needed. if repos.id is None: repos.save() cset.set_field('repos', repos, quiet=True) cset.set_field('repos.is_active', True) # If we're activating an old repository, re-probe() it. # This will make sure the server still exists, but more # importantly it will update our latest-rev. Otherwise, # we'll soon start downloading all the revisions we missed # while the repository was inactive! # # Note that probe() does not explicitly save() the # repository, but these changes will be saved automatically # by our changeset since we touched repos.is_active. if repos.location: repos.get_client().probe()
class EditPostForm(forms.Form): title = forms.CharField() listed = forms.BooleanField( required=False, widget=forms.CheckboxInput(attrs={'class': 'checkbox'}), ) content = forms.CharField(widget=forms.Textarea, )
class PostForm(djangoforms.ModelForm): # log = logging.getLogger() title = forms.CharField(widget=forms.TextInput(attrs={'id':'name'})) body = forms.CharField(widget=forms.Textarea(attrs={ 'id':'message', 'rows': 10, 'cols': 20})) body_markup = forms.ChoiceField( choices=[(k, v[0]) for k, v in markup.MARKUP_MAP.iteritems()]) tags = forms.CharField(widget=forms.Textarea(attrs={'rows': 5, 'cols': 20})) draft = forms.BooleanField(required=False) image_url = forms.CharField(required=False, widget=forms.TextInput(attrs={'id':'image_url'})) if common.PROD: url = '%s/api/authors' % (config.main_site_origin) else: url = '%s/api/authors' % (config.main_site_test_origin) sorted_profiles = [] try: response = urlfetch.fetch(url) if response.status_code == 200: sorted_profiles = simplejson.loads(response.content).keys() except urlfetch.DownloadError: pass author_id = forms.ChoiceField( choices=[(id,id) for id in sorted_profiles]) IMAGE_STYLES = (('top','top'), ('left','left'), ('right','right')) image_style = forms.ChoiceField(required=False, choices=IMAGE_STYLES) class Meta: model = models.BlogPost fields = [ 'title', 'body', 'tags', 'author_id', 'image_url', 'image_style' ]
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 RedirectionForm(forms.Form): experiment_name = forms.CharField(label="Experiment name") targets = forms.CharField(label="Target URLs", widget=forms.Textarea(attrs={ 'rows': '10', 'cols': '70' })) stratify = forms.BooleanField(label="Stratify", required=False)
def __init__(self, *args, **kwargs): products = kwargs.pop('products', None) super(InventoryForm, self).__init__(*args, **kwargs) if not products: products = Product.objects.all().order_by('slug') for product in products: subtypes = product.get_subtypes() qtyclasses = ('text', 'qty') + subtypes qtyclasses = " ".join(qtyclasses) kw = { 'label': product.slug, 'help_text': product.name, 'initial': product.items_in_stock, 'widget': forms.TextInput(attrs={'class': qtyclasses}) } qty = forms.IntegerField(**kw) self.fields['qty__%s' % product.slug] = qty qty.slug = product.slug qty.product_id = product.id qty.subtypes = " ".join(subtypes) kw['initial'] = product.unit_price kw['required'] = False kw['widget'] = forms.TextInput(attrs={'class': "text price"}) price = forms.DecimalField(**kw) price.slug = product.slug self.fields['price__%s' % product.slug] = price kw['initial'] = product.active kw['widget'] = forms.CheckboxInput( attrs={'class': "checkbox active"}) active = forms.BooleanField(**kw) active.slug = product.slug self.fields['active__%s' % product.slug] = active kw['initial'] = product.featured kw['widget'] = forms.CheckboxInput( attrs={'class': "checkbox featured"}) featured = forms.BooleanField(**kw) featured.slug = product.slug self.fields['featured__%s' % product.slug] = featured
def formfield(self, **kwargs): defaults = { 'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text } defaults.update(kwargs) return forms.BooleanField(**defaults)
class CommentForm(forms.Form): id = forms.CharField(widget=forms.HiddenInput) name = forms.CharField(max_length=64) url = forms.URLField(max_length=128, required=False) comment = forms.CharField(widget=forms.Textarea(attrs={ 'rows': 8, 'cols': 60 })) remember = forms.BooleanField(initial=True, required=False)
class RSVPForm(forms.Form): name = forms.CharField(widget=DijitText) will_attend = forms.BooleanField(widget=DijitBoolean, label="Will Attend?", required=False) num_guests = forms.IntegerField(widget=DijitNumberSpinner, required=False, label="Total Number of Guests") additional_guests = forms.CharField(widget=DijitTextArea, required=False, label="Additional Guest Names")
class EditBotForm(forms.Form): filter_mode = forms.ChoiceField( choices = models.filter_mode_choices, widget = forms.RadioSelect, ) project_list = forms.CharField( required = False, widget = forms.Textarea, ) show_project_names = forms.BooleanField( required = False, widget = forms.CheckboxInput(attrs = {'class': 'checkbox'}), ) def __init__(self, data=None): forms.Form.__init__(self, data) self.filter_modes = formtools.RadioChoices(self['filter_mode'], models.FILTER) def clean_filter_mode(self): return int(self.cleaned_data['filter_mode']) def clean_project_list(self): # Remove extra whitespace, split into individual projects. projects = [] for line in self.cleaned_data['project_list'].split('\n'): line = line.strip() if line: projects.append(line) # Is the project list required? if int(self.data['filter_mode']) == models.FILTER.PROJECT_LIST and not projects: raise forms.ValidationError("Please enter at least one project.") return '\n'.join(projects) custom_ruleset = forms.CharField( required = False, widget = forms.Textarea, ) def clean_custom_ruleset(self): # Empty rulesets are okay if we aren't using them. We never # allow a ruleset to be stored if it isn't well-formed and # valid. allow_empty = int(self.data['filter_mode']) != models.FILTER.CUSTOM # Use LibCIA to validate the ruleset. It would be nice to # hilight errors, or even interactively validate rulesets on # the client side.. but this is sufficient for now. return models.validate_ruleset(self.cleaned_data['custom_ruleset'], allow_empty) def apply(self, cset): cset.set_field_dict(self.cleaned_data) cset.asset.syncToServer()
class CacheDeleteForm(forms.Form): tag = forms.CharField('Key to delete', required=False) children = forms.BooleanField('Include Children?', initial=True) kill_all = forms.BooleanField('Delete all keys?', initial=False) def delete_cache(self): data = self.cleaned_data if data['kill_all']: caching.cache_delete() result = "Deleted all keys" elif data['tag']: caching.cache_delete(data['tag'], children=data['children']) if data['children']: result = "Deleted %s and children" % data['tag'] else: result = "Deleted %s" % data['tag'] else: result = "Nothing selected to delete" log.debug(result) return result
class EditForm(forms.Form): username = forms.RegexField('^[a-zA-Z0-9_]*$', max_length=30) is_active = forms.BooleanField(required = False) 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', required = False) pw2 = forms.CharField(widget = forms.PasswordInput, label = 'Password (again)', required = False)
def __init__(self, *args, **kwargs): debugOutput("Creating") super(self.__class__, self).__init__(*args, **kwargs) # Add some fields roles = wikidbase.core.security.getRoleNames() permissions = wikidbase.core.security.getPermissionsList() for role in roles: for category in permissions: for permission in permissions[category]: initial = wikidbase.core.security.roleHasPermission( role, permission) self.fields[self.getFieldName( role, category, permission)] = newforms.BooleanField(required=False, initial=initial)
class PostForm(djangoforms.ModelForm): title = forms.CharField(widget=forms.TextInput(attrs={'id': 'name'})) body = forms.CharField(widget=forms.Textarea(attrs={ 'id': 'message', 'rows': 10, 'cols': 20 })) body_markup = forms.ChoiceField( choices=[(k, v[0]) for k, v in markup.MARKUP_MAP.iteritems()]) tags = forms.CharField(widget=forms.Textarea(attrs={ 'rows': 5, 'cols': 20 })) draft = forms.BooleanField(required=False) class Meta: model = models.BlogPost fields = ['title', 'body', 'tags']
class PreferencesForm(forms.Form): """ Returns basic preferences form containing: source(s) to search alert method(s) criteria """ sources_choices = [] for source in Source.objects.all(): sources_choices.append((source.id, source.name)) sources = forms.MultipleChoiceField(widget=CheckboxSelectMultiple(), choices=sources_choices, required=False) alert_methods_choices = ( ('mail', 'E-Mail'), ('rss', 'RSS'), ) alert_methods = forms.MultipleChoiceField(widget=CheckboxSelectMultiple(), choices=alert_methods_choices, required=False) enable = forms.BooleanField(required=False) def save(self, user): """ Overrides save method to add form values to the correct place in the db for this user """ user_profile = user.get_profile() # set sources if self.cleaned_data.has_key('sources'): user_profile.sources.clear() for source_id in self.cleaned_data.get('sources', []): user_profile.sources.add(source_id) # set alert methods if self.cleaned_data.has_key('alert_methods'): user_profile.alert_methods.clear() for alert_method in self.cleaned_data.get('alert_methods', []): alert_method_obj = AlertMethod.objects.get(name=alert_method) user_profile.alert_methods.add(alert_method_obj)
class LoginForm(forms.Form): username = forms.CharField(label='Username', ) password = forms.CharField( label='Password', widget=forms.PasswordInput, ) remember_me = forms.BooleanField( label='Remember me on this computer', required=False, ) person = None account = None def clean(self): if self._errors: return self.person = Person.authenticate( self.data['username'], self.account, self.data['password'], ) if self.person is None: raise forms.ValidationError( "Your username and password didn't match. Did you spell them right?", ) return self.cleaned_data def login(self, request): self.account = request.account if self.is_valid(): request.session[ settings. PERSISTENT_SESSION_KEY] = self.cleaned_data['remember_me'] self.person.login(request) return True return False
class FormatForm(forms.Form): canonical = forms.BooleanField(required=False) explicit_start = forms.BooleanField(required=False) explicit_end = forms.BooleanField(required=False) allow_unicode = forms.BooleanField(required=False) styles = [(0, 'Default'), ('"', 'Double quote - "'), ("'", "Single quote - '")] default_style = forms.ChoiceField(choices=styles) flow_styles = [(1, 'Default'), (2, 'Block style'), (3, "Flow style")] default_flow_style = forms.ChoiceField(choices=flow_styles) indents = [(1, '1'), (2, '2'), (4, '4'), (8, '8')] indent = forms.ChoiceField(choices=indents, initial='4') widths = [(20, '20'), (40, '40'), (60, '60'), (80, '80'), (100, '100'), (120, '120')] width = forms.ChoiceField(choices=widths) versions = [(0, '1.0'), (1, '1.1')] yaml_version = forms.ChoiceField(choices=versions) show_version = forms.BooleanField(required=False) show_events = forms.BooleanField(required=False) show_tokens = forms.BooleanField(required=False) show_node = forms.BooleanField(required=False)
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 PostForm(djangoforms.ModelForm): title = forms.CharField(widget=forms.Textarea(attrs={ 'id': 'name', 'rows': 5, 'cols': 50 })) body = forms.CharField(widget=forms.Textarea(attrs={ 'id': 'message', 'rows': 20, 'cols': 50 })) tags = forms.CharField(widget=forms.Textarea(attrs={ 'rows': 5, 'cols': 20 })) draft = forms.BooleanField(required=False) class Meta: model = models.BlogPost fields = ['title', 'body', 'tags']
class ProjectForm(forms.Form): use_repository = forms.BooleanField( required=False, widget=forms.CheckboxInput(attrs={'class': 'checkbox'}), ) def apply(self, cset, request, repos): use_repository = bool(self.cleaned_data.get('use_repository')) if cset.asset.repos and cset.asset.repos.is_active and not use_repository: # Deactivate repository cset.set_field('repos.is_active', False) elif use_repository: # Activate repository, using either the asset's existing # repository or a temporary repository we created before # we knew it would definitely be needed. if repos.id is None: repos.save() cset.set_field('repos', repos, quiet=True) cset.set_field('repos.is_active', True)
class ExtendedContactInfoForm(ContactInfoForm): """Contact form which includes birthday and newsletter.""" dob = forms.DateField(required=False) newsletter = forms.BooleanField(label=_('Newsletter'), widget=forms.CheckboxInput(), required=False)
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 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 EditConfigForm(BaseConfigForm): deprecated = forms.BooleanField(required=False)
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