Exemple #1
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' ]
Exemple #2
0
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')
Exemple #3
0
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)
Exemple #4
0
                class ItemForm(djangoforms.ModelForm):

                    ## Custom djangoforms.ModelForm,
                    ## http://groups.google.com/group/google-appengine/browse_thread/thread/d3673d0ec7ead0e2

                    mail = forms.CharField(
                        label='您的邮箱(不会公开,无法更改)',
                        widget=forms.TextInput(
                            attrs={
                                'readonly': '',
                                'size': '30',
                                'maxlength': '30',
                                'value': EditedUser.user.email()
                            }))
                    #urlname =forms.CharField(label='URL显示地址',widget=forms.TextInput(attrs={'size':'30','maxlength':'30','value':CurrentUser.urlname}))
                    dispname = forms.CharField(
                        label='显示名称',
                        widget=forms.TextInput(
                            attrs={
                                'size': '30',
                                'maxlength': '30',
                                'value': EditedUser.dispname,
                                'class': 'sl'
                            }))
                    website = forms.CharField(
                        label='您的网址(请加http://)',
                        widget=forms.TextInput(
                            attrs={
                                'size': '36',
                                'maxlength': '36',
                                'value': EditedUser.website,
                                'class': 'sl'
                            }))
                    ##Please reference more from the URL

                    #notify_dailybriefing = forms.BooleanField(label='每日邮件提醒',widget=forms.CheckboxInput(attrs={'checked':EditedUser.notify_dailybriefing}))
                    #notify_dailybriefing_time = forms.CharField(label='每日邮件提醒时间', widget=forms.TextInput(attrs={'value':EditedUser.notify_dailybriefing_time,'class':'sl'}))
                    #notify_addedasfriend = forms.BooleanField(label='用户添加好友邮件提醒',widget=forms.CheckboxInput(attrs={'checked':EditedUser.notify_addedasfriend}))

                    apikey = forms.CharField(label="ApiKey(请勿泄露)",
                                             widget=forms.TextInput(
                                                 attrs={
                                                     'readonly': '',
                                                     'class': 'sl',
                                                     'value': EditedUser.apikey
                                                 }))

                    class Meta:
                        model = tarsusaUser
                        #exclude =['user','userid','usedtags','urlname','friends','datejoinin']
                        exclude = [
                            'user', 'userid', 'usedtags', 'urlname', 'friends',
                            'datejoinin', 'notify_dailybriefing',
                            'notify_dailybriefing_time', 'notify_addedasfriend'
                        ]
Exemple #5
0
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)
Exemple #6
0
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')
Exemple #7
0
class MapParametersForm(forms.Form):
    "Класс формы для указания параметров карты"
#    device         = forms.ModelChoiceField(Device.objects.all())
    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="гггг-мм-дд чч:мм:сс")
    
    def __init__(self, account, *args, **kwargs):
        """
        Конструктор переопределен для создания поля "device", 
        список значений для которого фильтруется в соответствии с текущим Аккаунтом  
        """
        super(MapParametersForm, self).__init__(*args, **kwargs)
        self.fields["device"] = forms.ModelChoiceField(Device.objects.filter(account__exact=account), label="Устройство")
Exemple #8
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)
Exemple #9
0
class StatsMetadataForm(forms.Form):
    title = forms.CharField(widget=forms.TextInput(attrs={'class': 'text'}), )
    subtitle = forms.CharField(
        required=False,
        widget=forms.TextInput(attrs={'class': 'text'}),
    )
    url = forms.URLField(
        required=False,
        widget=forms.TextInput(attrs={'class': 'text'}),
        # Disabled for now, since it seems to imply required=True.
        # verify_exists = True,
    )
    description = forms.CharField(
        required=False,
        widget=forms.Textarea,
    )
    photo_id = forms.IntegerField(
        required=False,
        widget=ImageWidget,
    )
    icon_id = forms.IntegerField(
        required=False,
        widget=ImageWidget,
    )

    def clean_subtitle(self):
        return self.cleaned_data.get('subtitle') or None

    def clean_url(self):
        return self.cleaned_data.get('url') or None

    def clean_description(self):
        return self.cleaned_data.get('description') or None

    def clean_photo_id(self):
        return self.cleaned_data.get('photo_id') or None

    def clean_icon_id(self):
        return self.cleaned_data.get('icon_id') or None

    def apply(self, cset):
        target = cset.asset.target
        cset.set_field_dict(self.cleaned_data, prefix='target.')

        if target.photo:
            target.photo.reference()
        if target.icon:
            target.icon.reference()
Exemple #10
0
    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
Exemple #11
0
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()
Exemple #12
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
Exemple #13
0
class CommentForm(forms.Form):
    """
    A form representing a comment on an entry.
    """
    person_name = forms.CharField(
        label = _("Name (required)"),
        widget = forms.TextInput(attrs=dict(size="22")))
        
    comment = forms.CharField(
        label = "",
        widget = forms.Textarea(attrs=dict(cols="60")))
Exemple #14
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']
Exemple #15
0
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"])
Exemple #16
0
class AddStatsAssetForm(forms.Form):
    name = forms.CharField(widget=forms.TextInput(attrs={'class': 'text'}), )
Exemple #17
0
 def __init__(self,attrs=None):
     widgets = (forms.TextInput(attrs=attrs), forms.TextInput(attrs=attrs))        
     super(RangeWidget, self).__init__(widgets, attrs)