Esempio n. 1
0
class AccountForm(forms.Form, ManualFormHelpers):
    name = forms.CharField(
        label="Company / Organization",
        min_length=2,
        max_length=30,
    )
    timezone = forms.ChoiceField(label="Time zone",
                                 choices=settings.ACCOUNT_TIME_ZONES)
    subdomain = forms.CharField(
        min_length=2,
        max_length=30,
    )
    domain = forms.ChoiceField(choices=settings.ACCOUNT_DOMAINS)

    def clean_subdomain(self):
        if not self.cleaned_data['subdomain'].isalnum():
            raise forms.ValidationError(
                "Your subdomain can only include letters and numbers.")
        return self.cleaned_data['subdomain']

    def update_account(self, account):
        for n in ['name', 'subdomain', 'domain', 'timezone']:
            setattr(account, n, self.cleaned_data[n])
        if not account.validate():
            account.save()
            return account
        else:
            logging.debug(str(account.subscription_level_id))
            logging.debug('UPDATE_ACCOUNT validation errors: %s' %
                          str(account.validate()))
            raise ValueError
Esempio n. 2
0
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' ]
Esempio n. 3
0
class inputForm(forms.Form):

    betType = forms.ChoiceField(choices=BETTYPE_CHOICES,
                                label='Betting Strategy')
    nDeck = forms.ChoiceField(choices=NDECK_CHOICES, label='Number of Decks')
    nSim = forms.ChoiceField(choices=NSIM_CHOICES,
                             label='Number of Simulation')
    minimumBet = forms.ChoiceField(choices=MINIMUM, label='Minimum Bet')
    maximumBet = forms.ChoiceField(choices=MAXIMUM, label='Maximum Bet')
Esempio n. 4
0
class ScheduleBuilderForm(forms.Form):
    _courses = [(c.id, str(c)) for c in Course.objects.filter(current=True)]
    _hours = [(x, "%s:00" % (x % 12)) for x in [8,9,10,11,13,14,15,16]]
    _lengths = [(x, "%s hours" % x) for x in [1,2,3,4]]
    _instructors = [(p.instructor_letter, str(p)) for p in Person.objects.filter(kind=FACULTY_KIND)]
    _rooms = [(r.id, str(r)) for r in Room.objects.all()]
    course = forms.ChoiceField(choices=_courses)
    start_time = forms.ChoiceField(choices=_hours)
    length = forms.ChoiceField(choices=_lengths)
    room = forms.ChoiceField(choices=_rooms)
    sections = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=SECTION_CHOICES)
    instructors = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=_instructors, required=False)
Esempio n. 5
0
class DataqueryForm(forms.Form):
    
    FORMAT="%Y-%m-%d %H:%M:%S"
    td=datetime.datetime.utcnow()
    NOW=td.strftime(FORMAT)
    yd = datetime.datetime.utcnow() - datetime.timedelta(1)
    YESTERDAY=yd.strftime(FORMAT)
    
    starttime = forms.DateTimeField( initial=YESTERDAY)
    endtime = forms.DateTimeField( initial=NOW)
    sitename = forms.ChoiceField(choices=SITE_CHOICES)
    datatype = forms.ChoiceField(choices=DTYPE_CHOICES, initial="counts")
Esempio n. 6
0
class AnalysisForm(forms.Form):
    
    FORMAT="%Y-%m-%d %H:%M:%S"
    td=datetime.datetime.utcnow()
    NOW=td.strftime(FORMAT)
    yd = datetime.datetime.utcnow() - datetime.timedelta(1)
    YESTERDAY=yd.strftime(FORMAT)
    
    starttime = forms.DateTimeField( label="Start Time", initial=YESTERDAY)
    endtime = forms.DateTimeField( label="End Time", initial=NOW)
    sitename = forms.ChoiceField(label="Site Name", choices=SITE_CHOICES)
    format = forms.ChoiceField(label="Output Format", choices=FORMAT_CHOICES, initial="txt")
    datatype = forms.ChoiceField(label="Data Type" , choices=ATYPE_CHOICES, initial="counts")
    filtertype = forms.ChoiceField(label="Processing Type", choices=FILTER_CHOICES, initial="avg")
    interval = forms.IntegerField(label="Averaging Interval (minutes)", initial=30)
Esempio n. 7
0
 def __init__(self, listChoices, sortChoices, *args, **kwargs):
     debugOutput("Creating")
     super(FieldConfigForm, self).__init__(*args, **kwargs)
     self.fields["field_type"] = newforms.ChoiceField(
         required=True,
         choices=listChoices)  #, widget=newforms.RadioSelect)
     self.fields["list_sort"] = newforms.ChoiceField(
         required=True,
         choices=sortChoices)  #, widget=newforms.RadioSelect)
     self.fields["list_values"] = newforms.CharField(
         required=False,
         widget=newforms.Textarea(attrs={
             "cols": 35,
             "rows": 15
         }))
Esempio n. 8
0
    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
Esempio n. 9
0
    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
Esempio n. 10
0
class SimplePayShipForm(forms.Form):
    shipping = forms.ChoiceField(widget=forms.RadioSelect(), required=False)
    discount = forms.CharField(max_length=30, required=False)

    def __init__(self, request, paymentmodule, *args, **kwargs):
        super(SimplePayShipForm, self).__init__(*args, **kwargs)

        self.tempCart = Cart.objects.get(id=request.session['cart'])
        self.tempContact = Contact.from_request(request)
        shipping_choices, shipping_dict = _get_shipping_choices(
            paymentmodule, self.tempCart, self.tempContact)
        self.fields['shipping'].choices = shipping_choices
        self.shipping_dict = shipping_dict

    def clean_shipping(self):
        shipping = self.cleaned_data['shipping']
        if not shipping and self.tempCart.is_shippable:
            raise forms.ValidationError(_('This field is required.'))
        return shipping

    def clean_discount(self):
        """ Check if discount exists and is valid. """
        data = self.cleaned_data['discount']
        if data:
            try:
                discount = Discount.objects.get(code=data, active=True)
            except Discount.DoesNotExist:
                raise forms.ValidationError(_('Invalid discount.'))
            valid, msg = discount.isValid(self.tempCart)
            if not valid:
                raise forms.ValidationError(msg)
            # TODO: validate that it can work with these products
        return data
Esempio n. 11
0
class ApplianceForm(forms.Form):
    url = forms.URLField()
    email = forms.EmailField()

    appliance_type = forms.ChoiceField(choices = [('', 'Unknown'),
                                                  ('EC2', 'Amazon EC2'),
                                                  ('VMX', 'VMware'),
                                                  ('Devel', 'Development')])
Esempio n. 12
0
    def __init__(self, *args, **kwargs):
        debugOutput("Creating")

        super(self.__class__, self).__init__(*args, **kwargs)

        # Get a list of contexts.
        types = []
        wikidbaseContexts = wikidbase.core.context.getContexts()
        for nContext in wikidbaseContexts:
            types.append(wikidbaseContexts[nContext].contextNameVariations.
                         getMostCommon())
        types = [(x, x.capitalize()) for x in types]

        self.fields["relationtypea"] = newforms.ChoiceField(choices=types,
                                                            required=False)
        self.fields["relationtypeb"] = newforms.ChoiceField(choices=types,
                                                            required=False)
        self.fields["relationnamea"] = newforms.CharField(required=False)
        self.fields["relationnameb"] = newforms.CharField(required=False)
Esempio n. 13
0
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}")
Esempio n. 14
0
class SettingsForm(forms.Form):
    #	AccountStatus = forms.CharField()
    #	PrivacyConfigurationFile = forms.CharField()
    #	PrivacyPolicyFile = forms.CharField()
    #	PatientBrochureFile = forms.CharField()
    #	TemporaryAccountRetentionTime = forms.CharField()
    ApplianceMode = forms.ChoiceField(choices=[('0', 'Development'),
                                               ('1', 'Test'), ('2', 'Demo'),
                                               ('3', 'Production')],
                                      initial='0')

    OnlineRegistration = forms.ChoiceField(
        choices=[('0', 'Disabled'), ('1', 'Enabled')],
        help_text="Can new users register online")

    OpenIDMode = forms.ChoiceField(
        choices=[('0', 'Disabled'), ('1', 'Whitelist'), ('2', 'Open')],
        initial='0',
        help_text='Which OpenID logins are accepted')
Esempio n. 15
0
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()
Esempio n. 16
0
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)
Esempio n. 17
0
class PaymentContactInfoForm(ContactInfoForm):
    _choices = payment_choices()
    if len(_choices) > 0:
        if len(_choices) > 1:
            _paymentwidget = forms.RadioSelect
        else:
            _paymentwidget = forms.HiddenInput(attrs={'value': _choices[0][0]})

        paymentmethod = forms.ChoiceField(label=_('Payment method'),
                                          choices=_choices,
                                          widget=_paymentwidget,
                                          required=True)
Esempio n. 18
0
class CreateConfigForm(BaseConfigForm):
  type = forms.ChoiceField(
      widget=forms.widgets.Select(attrs={'id':"imagetype"}),
      choices=(
        ("kernel", "Linux Kernel"),
        ("image", "Raw image file"),
        ("memdisk", "Disk image"),
        ("iso", "CD ISO Image")),
      initial="kernel")
  kernel = forms.URLField(widget=forms.widgets.TextInput(attrs={'id':"kernel"}),
                          label="Kernel/Image")
  initrd = forms.URLField(widget=forms.widgets.TextInput(attrs={'id':"initrd"}),
                          required=False)
  args = forms.CharField(widget=forms.widgets.TextInput(attrs={'id':"args"}),
                         required=False)
Esempio n. 19
0
#------------------------------------------------------------------------------
class ReportsForm(forms.Form):
    "Класс формы для отчета"
    report_kind    = forms.ChoiceField(label="Вид отчета", choices=REPORT_KINDS, help_text="Выберите вид отчета")
#    device         = forms.ModelChoiceField(queryset=Device.objects.filter())
    interval_begin = forms.DateTimeField(label="Начало периода", widget=forms.TextInput(attrs={"class" : "vDateField"}), help_text="гггг-мм-дд чч:мм:сс")
    interval_end   = forms.DateTimeField(label="Конец периода", widget=forms.TextInput(attrs={"class" : "vDateField"}), help_text="гггг-мм-дд чч:мм:сс")
    speed_limit    = forms.IntegerField(label="Ограничение скорости", initial=72,  help_text="скорость в км/ч")
    
    def __init__(self, account, *args, **kwargs):
        """
        Конструктор переопределен для создания поля "device", 
        список значений для которого фильтруется в соответствии с текущим Аккаунтом  
        """
        super(ReportsForm, self).__init__(*args, **kwargs)
Esempio n. 20
0
    def __init__(self, *args, **kwargs):
        debugOutput("Creating")

        if "fields" in kwargs and kwargs["fields"]:
            fields = kwargs["fields"]
            del kwargs["fields"]
        else:
            fields = []

        super(self.__class__, self).__init__(*args, **kwargs)

        choices = [("above__" + nField, "Above " + fields[nField])
                   for nField in fields]
        choices.append(("bottom", "Bellow all fields"))
        self.fields["position"] = newforms.ChoiceField(choices=choices,
                                                       required=True)
Esempio n. 21
0
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']
Esempio n. 22
0
class QuestionForm(forms.Form):
	answers = forms.ChoiceField(widget=forms.RadioSelect(), label=u"Please select a answer:")
	
	def __init__(self, question, *args, **kwargs):
		super(QuestionForm, self).__init__(*args, **kwargs)
		self.question = question.question
		answers = question.answers.order_by('weight')
		self.fields['answers'].choices = [(i, a.answer) for i, a in enumerate(answers)]
		
		for pos, answer in enumerate(answers):
			if answer.id == question.correct_answer_id:
				self.correct = pos
			break
	
	def is_correct(self):
		if not self.is_valid():
			return False
		
		return self.cleaned_data['answers'] == str(self.correct)
Esempio n. 23
0
class PageForm(djangoforms.ModelForm):
  path = forms.RegexField(
    widget=forms.TextInput(attrs={'id':'path'}), 
    regex='(/[a-zA-Z0-9/]+)')
  title = forms.CharField(widget=forms.TextInput(attrs={'id':'title'}))
  template = forms.ChoiceField(choices=config.page_templates.items())
  body = forms.CharField(widget=forms.Textarea(attrs={
      'id':'body',
      'rows': 10,
      'cols': 20}))
  class Meta:
    model = models.Page
    fields = [ 'path', 'title', 'template', 'body' ]

  def clean_path(self):
    data = self._cleaned_data()['path']
    existing_page = models.Page.get_by_key_name(data)
    if not data and existing_page:
      raise forms.ValidationError("The given path already exists.")
    return data
Esempio n. 24
0
def customized_editor(user, settings):
    "Customize the setting editor based on the current user and setting list"
    base_fields = SortedDict()
    for setting in settings:
        perm = '%s.can_edit_%s_settings' % (setting.module_name.split('.')[-2],
                                            setting.class_name.lower())
        if user.has_perm(perm):
            # Add the field to the customized field list
            storage = get_setting_storage(*setting.key)
            kwargs = {
                'label': setting.description,
                'help_text': setting.help_text,
                # Provide current setting values for initializing the form
                'initial': setting.to_editor(storage.value),
            }
            if setting.choices:
                field = forms.ChoiceField(choices=setting.choices, **kwargs)
            else:
                field = setting.field(**kwargs)
            base_fields['%s__%s__%s' % setting.key] = field
    return type('SettingsEditor', (SettingsEditor, ),
                {'base_fields': base_fields})
Esempio n. 25
0
class MoveNodeForm(forms.Form):
    """
    A form which allows the user to move a given node from one location
    in its tree to another, with optional restriction of the nodes which
    are valid target nodes for the move.
    """
    POSITION_FIRST_CHILD = 'first-child'
    POSITION_LAST_CHILD = 'last-child'
    POSITION_LEFT = 'left'
    POSITION_RIGHT = 'right'

    POSITION_CHOICES = (
        (POSITION_FIRST_CHILD, _('First child')),
        (POSITION_LAST_CHILD, _('Last child')),
        (POSITION_LEFT, _('Left sibling')),
        (POSITION_RIGHT, _('Right sibling')),
    )

    target = forms.ModelChoiceField(queryset=None)
    position = forms.ChoiceField(choices=POSITION_CHOICES,
                                 initial=POSITION_FIRST_CHILD)

    def __init__(self, node, *args, **kwargs):
        """
        The ``node`` to be moved must be provided. The following keyword
        arguments are also accepted::

        ``valid_targets``
           Specifies a ``QuerySet`` of valid targets for the move. If
           not provided, valid targets will consist of everything other
           node of the same type, apart from the node itself and any
           descendants.

           For example, if you want to restrict the node to moving
           within its own tree, pass a ``QuerySet`` containing
           everything in the node's tree except itself and its
           descendants (to prevent invalid moves) and the root node (as
           a user could choose to make the node a sibling of the root
           node).

        ``target_select_size``
           The size of the select element used for the target node.
           Defaults to ``10``.
        """
        valid_targets = kwargs.pop('valid_targets', None)
        target_select_size = kwargs.pop('target_select_size', 10)
        super(MoveNodeForm, self).__init__(*args, **kwargs)
        self.node = node
        opts = node._meta
        if valid_targets is None:
            valid_targets = node._tree_manager.exclude(
                **{
                    opts.tree_id_attr: getattr(node, opts.tree_id_attr),
                    '%s__gte' % opts.left_attr: getattr(node, opts.left_attr),
                    '%s__lte' % opts.right_attr: getattr(
                        node, opts.right_attr),
                })
        self.fields['target'].queryset = valid_targets
        self.fields['target'].choices = \
            [(target.pk, '%s %s' % ('---' * getattr(target, opts.level_attr),
                                    unicode(target)))
             for target in valid_targets]
        self.fields['target'].widget.attrs['size'] = target_select_size

    def save(self):
        """
        Attempts to move the node using the selected target and
        position.

        If an invalid move is attempted, the related error message will
        be added to the form's non-field errors and the error will be
        re-raised. Callers should attempt to catch ``InvalidNode`` to
        redisplay the form with the error, should it occur.
        """
        try:
            self.node.move_to(self.cleaned_data['target'],
                              self.cleaned_data['position'])
            return self.node
        except InvalidMove, e:
            self.errors[NON_FIELD_ERRORS] = ErrorList(e)
            raise
Esempio n. 26
0
 def choice_field(self, **kwargs):
     if self.hidden:
         kwargs['widget'] = forms.MultipleHiddenInput()
     return forms.ChoiceField(choices=self.choices, **kwargs)
Esempio n. 27
0
class CreditPayShipForm(forms.Form):
    credit_type = forms.ChoiceField()
    credit_number = forms.CharField(max_length=20)
    month_expires = forms.ChoiceField(choices=[(month, month)
                                               for month in range(1, 13)])
    year_expires = forms.ChoiceField()
    ccv = forms.IntegerField()  # find min_length
    shipping = forms.ChoiceField(widget=forms.RadioSelect(), required=False)
    discount = forms.CharField(max_length=30, required=False)

    def __init__(self, request, paymentmodule, *args, **kwargs):
        creditchoices = paymentmodule.CREDITCHOICES.choice_values
        super(CreditPayShipForm, self).__init__(*args, **kwargs)

        self.fields['credit_type'].choices = creditchoices

        year_now = datetime.date.today().year
        self.fields['year_expires'].choices = [
            (year, year) for year in range(year_now, year_now + 6)
        ]

        self.tempCart = Cart.objects.get(id=request.session['cart'])
        self.tempContact = Contact.from_request(request)

        shipping_choices, shipping_dict = _get_shipping_choices(
            paymentmodule, self.tempCart, self.tempContact)
        self.fields['shipping'].choices = shipping_choices
        self.shipping_dict = shipping_dict

    def clean_credit_number(self):
        """ Check if credit card is valid. """
        credit_number = self.cleaned_data['credit_number']
        card = CreditCard(credit_number, self.cleaned_data['credit_type'])
        results, msg = card.verifyCardTypeandNumber()
        if not results:
            raise forms.ValidationError(msg)
        return credit_number

    def clean_month_expires(self):
        return int(self.cleaned_data['month_expires'])

    def clean_year_expires(self):
        """ Check if credit card has expired. """
        month = self.cleaned_data['month_expires']
        year = int(self.cleaned_data['year_expires'])
        max_day = calendar.monthrange(year, month)[1]
        if datetime.date.today() > datetime.date(
                year=year, month=month, day=max_day):
            raise forms.ValidationError(_('Your card has expired.'))
        return year

    def clean_shipping(self):
        shipping = self.cleaned_data['shipping']
        if not shipping and self.tempCart.is_shippable:
            raise forms.ValidationError(_('This field is required.'))
        return shipping

    def clean_discount(self):
        """ Check if discount exists and if it applies to these products """
        data = self.cleaned_data['discount']
        if data:
            discount = Discount.objects.filter(code=data).filter(active=True)
            if discount.count() == 0:
                raise forms.ValidationError(_('Invalid discount.'))
            valid, msg = discount[0].isValid(self.tempCart)
            if not valid:
                raise forms.ValidationError(msg)
        return data
Esempio n. 28
0
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
Esempio n. 29
0
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}))
Esempio n. 30
0
class EditAssetForm(forms.Form):
    access = forms.ChoiceField(
        choices=models.access_choices,
        widget=forms.RadioSelect,
    )

    def __init__(self, data=None):
        forms.Form.__init__(self, data)
        self.access_levels = formtools.RadioChoices(self['access'],
                                                    models.ACCESS)

    def clean_access(self):
        return int(self.cleaned_data['access'])

    def should_delete(self):
        """Are we removing access to this asset?"""
        return self.cleaned_data['access'] == models.ACCESS.NONE

    def delete(self, request, user_asset):
        """Delete this UserAsset, create a message indicating that we
           were successful, then redirect back to the 'add' page.
           """
        user_asset.delete()
        request.user.message_set.create(message="Removed access to %s" %
                                        user_asset.asset)
        return HttpResponseRedirect("/account/%s/add/" %
                                    user_asset.asset._meta.asset_type)

    def apply(self, cset, request, user_asset):
        """Apply changes to a UserAsset, saving information about
           those changes in the provided changeset.
           """
        new_access = self.cleaned_data['access']
        if new_access != user_asset.access:

            if new_access == models.ACCESS.NONE:
                # We'll actually do the deletion later

                cset.set_meta('_lost_access')

            elif new_access == models.ACCESS.COMMUNITY:
                # Decreasing the access level

                request.user.message_set.create(
                    message="You now have community-level access to %s" %
                    user_asset.asset)
                assert user_asset.access > new_access
                cset.set_meta('_community_access')
                user_asset.access = new_access
                user_asset.save()

            elif new_access == models.ACCESS.EXCLUSIVE:
                # Increasting the access level. Gaining exclusive
                # access also means revoking access from any other
                # (community-access) users!

                request.user.message_set.create(
                    message="You have taken exclusive access to %s" %
                    user_asset.asset)
                cset.set_meta('_exclusive_access')
                user_asset.access = new_access
                user_asset.save()
                user_asset.asset.assets.exclude(user=request.user).delete()