コード例 #1
0
class RegistrationConfirmationForm(forms.Form):
    username = forms.CharField(label=u'User Name', max_length=30, required=True, validators=[validators.RegexValidator(
        r'^[\w.@+-]+$', 'Enter a valid username. This value may contain only letters, numbers and @/./+/-/_ characters.', 'invalid')])
    password = forms.CharField(
        label=u'Password', widget=forms.PasswordInput(), required=True)
    passwordconfirm = forms.CharField(
        label=u'Confirm Password', widget=forms.PasswordInput(), required=True)

    def __init__(self, user, token, token_generator=default_token_generator, *args, **kwargs):
        super(RegistrationConfirmationForm, self).__init__(*args, **kwargs)
        self.user = user
        self.token = token
        self.token_generator = token_generator
        if not self.check_token():
            self.fields = {}

    def check_token(self):
        if self.user and not self.user.is_active and self.token and self.token_generator:
            return self.token_generator.check_token(self.user, self.token)
        else:
            return False

    def clean_username(self):
        AuthUser = get_user_model()
        usersWithName = AuthUser.objects.filter(
            username__iexact=self.cleaned_data['username'])
        if not usersWithName.exists() or (usersWithName.count() == 1 and usersWithName[0] == self.user):
            return self.cleaned_data['username']
        raise forms.ValidationError(
            'Username {0} is already taken'.format(self.cleaned_data['username']))

    def clean_password(self):
        if not self.cleaned_data['password']:
            raise forms.ValidationError('Password must not be blank.')
        return self.cleaned_data['password']

    def clean(self):
        if not self.check_token():
            raise forms.ValidationError('User token pair is not valid.')
        if 'password' in self.cleaned_data and 'passwordconfirm' in self.cleaned_data:
            if self.cleaned_data['password'] != self.cleaned_data['passwordconfirm']:
                raise forms.ValidationError('Passwords must match.')
        return self.cleaned_data

    def save(self, commit=True):
        if self.user:
            self.user.username = self.cleaned_data['username']
            self.user.set_password(self.cleaned_data['password'])
            self.user.is_active = True
            if commit == True:
                self.user.save()
        else:
            raise forms.ValidationError('Could not save user.')
        return self.user
コード例 #2
0
 def __init__(self, event=None, *args, **kwargs):
     super(DonationEntryForm, self).__init__(*args, **kwargs)
     minDonationAmount = event.minimumdonation if event != None else Decimal(
         "1.00")
     self.fields['amount'] = forms.DecimalField(decimal_places=2, min_value=minDonationAmount, max_value=Decimal("100000"),  label="Donation Amount (min ${0})".format(
         minDonationAmount), widget=tracker.widgets.NumberInput(attrs={'id': 'iDonationAmount', 'min': str(minDonationAmount), 'step': '0.01'}), required=True)
     self.fields['comment'] = forms.CharField(
         widget=forms.Textarea, required=False)
     self.fields['requestedvisibility'] = forms.ChoiceField(
         initial='ALIAS', choices=models.Donation._meta.get_field('requestedvisibility').choices, label='Name Visibility')
     self.fields['requestedalias'] = forms.CharField(
         max_length=32, label='Preferred Alias', required=False)
     self.fields['requestedemail'] = forms.EmailField(
         max_length=128, label='Preferred Email', required=False)
     self.fields['requestedsolicitemail'] = forms.ChoiceField(
         initial='CURR', choices=models.Donation._meta.get_field('requestedsolicitemail').choices, label='Charity Email Opt In')
コード例 #3
0
    def __init__(self, amount=None, bids=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.amount = amount
        self.bids = bids

        # Build form fields
        if self.bids:
            for bid in self.bids:
                # If this is a target the user can select, add the amount field.
                if bid.allowuseroptions or bid.istarget:
                    self.fields['bid_amt_{}'.format(bid.id)] = forms.DecimalField(
                        decimal_places=2, max_digits=20, required=False, min_value=0,
                        widget=tracker.widgets.NumberInput(attrs={'class': 'form-control bid-amount', 'step': '0.01',
                                                                  'placeholder': '$', 'min': '0'}))

                # If this is a user-options bid war parent, add an extra field for new option value.
                if bid.allowuseroptions:
                    self.fields['bid_new_option_name_{}'.format(bid.id)] = forms.CharField(
                        max_length=models.Bid._meta.get_field('name').max_length, required=False,
                        widget=forms.widgets.TextInput(attrs={'class': 'form-control bid-value',
                                                              'placeholder': 'Enter New Value'}))

                # Add amount fields for any bid war options.
                for option in bid.options.all():
                    if option.istarget:
                        self.fields['bid_amt_{}'.format(option.id)] = forms.DecimalField(
                            decimal_places=2, max_digits=20, required=False, min_value=0,
                            widget=tracker.widgets.NumberInput(attrs={'class': 'form-control bid-amount',
                                                                      'step': '0.01', 'placeholder': '$', 'min': '0'}))
コード例 #4
0
 def __init__(self, model, objects, *args, **kwargs):
     super(MergeObjectsForm, self).__init__(*args, **kwargs)
     self.model = model
     self.choices = []
     for objId in objects:
         self.choices.append(
             (objId, unicode(self.model.objects.get(id=objId))))
     self.fields['root'] = forms.ChoiceField(
         choices=self.choices, required=True)
     self.fields['objects'] = forms.CharField(initial=','.join(
         [str(i) for i in objects]), widget=forms.HiddenInput())
コード例 #5
0
class UsernameForm(forms.Form):
    username = forms.CharField(
        max_length=255,
        widget=forms.TextInput(attrs={'class': 'required username'}))

    def clean_username(self):
        if 'username' in self.cleaned_data:
            username = self.cleaned_data['username']
            if not re.match(r'^[a-zA-Z0-9_]+$', username):
                raise forms.ValidationError(
                    _("Usernames can only contain letters, numbers, and the underscore"))
            if username[:10] == 'openiduser':
                raise forms.ValidationError(
                    _("Username may not start with 'openiduser'"))
            if User.objects.filter(username=username).count() > 0:
                raise forms.ValidationError(_("Username already in use"))
            return self.cleaned_data['username']
コード例 #6
0
    def __init__(self, *args, **kwargs):
        super(PrizeAcceptanceForm, self).__init__(*args, **kwargs)
        self.accepted = None

        if 'data' in kwargs and kwargs['data'] != None:
            if 'accept' in kwargs['data']:
                self.accepted = True
            elif 'deny' in kwargs['data']:
                self.accepted = False

        self.fields['count'] = forms.ChoiceField(initial=self.instance.pendingcount, choices=list(map(lambda x: (x, x), range(1, self.instance.pendingcount + 1))), label='Count',
                                                 help_text='You were selected to win more than one copy of this prize, please select how many you would like to take, or press Deny All if you do not want any of them.')
        if self.instance.pendingcount == 1:
            self.fields['count'].widget = forms.HiddenInput()
        self.fields['total'] = forms.IntegerField(initial=self.instance.pendingcount, validators=[
                                                  positive], widget=forms.HiddenInput())
        self.fields['comments'] = forms.CharField(max_length=512, label='Notes', required=False,
                                                  help_text="Please put any additional notes here (such as if you have the option of customizing your prize before it is shipped, or additional delivery information).", widget=forms.Textarea(attrs=dict(cols=40, rows=2)))
コード例 #7
0
class DonationCredentialsForm(forms.Form):
    paypalemail = forms.EmailField(min_length=1, label="Paypal Email")
    amount = forms.DecimalField(
        decimal_places=2, min_value=Decimal('0.00'), label="Donation Amount")
    transactionid = forms.CharField(min_length=1, label="Transaction ID")
コード例 #8
0
class PrizeSubmissionForm(forms.Form):
    name = forms.CharField(max_length=64, required=True, label="Prize Name",
                           help_text="Please use a name that will uniquely identify your prize throughout the event.")
    description = forms.CharField(max_length=1024, required=True, label="Prize Description", widget=forms.Textarea,
                                  help_text="Briefly describe your prize, as you would like it to appear to the public. All descriptions are subject to editing at our discretion.")
    maxwinners = forms.IntegerField(required=True, initial=1, widget=tracker.widgets.NumberInput({'min': 1, 'max': 10}), label="Number of Copies",
                                    help_text="If you are submitting multiple copies of the same prize (e.g. multiple copies of the same print), specify how many. Otherwise, leave this at 1.")
    startrun = forms.fields.IntegerField(label="Suggested Start Game", required=False, widget=tracker.widgets.MegaFilterWidget(model="run"),
                                         help_text="If you feel your prize would fit with a specific game (or group of games), enter them here. Please specify the games in the order that they will appear in the marathon.")
    endrun = forms.fields.IntegerField(label="Suggested End Game", required=False, widget=tracker.widgets.MegaFilterWidget(model="run"),
                                       help_text="Leaving only one or the other field blank will simply set the prize to only cover the one game")
    extrainfo = forms.CharField(max_length=1024, required=False, label="Extra/Non-Public Information", widget=forms.Textarea,
                                help_text="Enter any additional information you feel the staff should know about your prize. This information will not be made public. ")
    estimatedvalue = forms.DecimalField(decimal_places=2, max_digits=20, required=True, label='Estimated Value', validators=[positive, nonzero],
                                        help_text="Estimate the actual value of the prize. If the prize is handmade, use your best judgement based on time spent creating it. Note that this is not the bid amount.")
    imageurl = forms.URLField(max_length=1024, label='Prize Image', required=True,
                              help_text=mark_safe("Enter the URL of an image of the prize. Please see our notes regarding prize images at the bottom of the form. Images are now required for prize submissions."))
    creatorname = forms.CharField(max_length=64, required=False, label="Prize Creator",
                                  help_text="Name of the creator of the prize. This is for crediting/promoting the people who created this prize (please fill this in even if you are the creator).")
    creatoremail = forms.EmailField(max_length=128, label='Prize Creator Email', required=False,
                                    help_text="Enter an e-mail if the creator of this prize accepts comissions and would like to be promoted through our marathon. Do not enter an e-mail unless they are known to accept comissions, or you have received their explicit consent.")
    creatorwebsite = forms.URLField(max_length=1024, label='Prize Creator Website', required=False,
                                    help_text="Enter the URL of the prize creator's website or online storefront if applicable.")
    agreement = forms.BooleanField(label="Agreement", help_text=mark_safe("""Check if you agree to the following: 
  <ul>
    <li>I am expected to ship the prize myself, and will keep a receipt to be reimbursed for the cost of shipping.</li>
    <li>I currently have the prize in my possesion, or can guarantee that I can obtain it within one week of the start of the marathon.</li>
    <li>I agree to communicate with the staff in a timely manner as neccessary regarding this prize.</li>
    <li>I agree that all contact information is correct has been provided with the consent of the respective parties.</li>
    <li>I agree that if the prize is no longer available, I will contact the staff immediately to withdraw it, and no later than one month of the start date of the marathon.</li>
  </ul>"""))

    def impl_clean_run(self, data):
        if not data:
            return None
        try:
            return models.SpeedRun.objects.get(id=data)
        except:
            raise forms.ValidationError("Invalid Run id.")

    def clean_startrun(self):
        return self.impl_clean_run(self.cleaned_data['startrun'])

    def clean_endrun(self):
        return self.impl_clean_run(self.cleaned_data['endrun'])

    def clean_name(self):
        basename = self.cleaned_data['name']
        prizes = models.Prize.objects.filter(name=basename)
        if not prizes.exists():
            return basename
        name = basename
        count = 1
        while prizes.exists():
            count += 1
            name = basename + ' ' + str(count)
            prizes = models.Prize.objects.filter(name=name)
        raise forms.ValidationError(
            'Prize name taken. Suggestion: "{0}"'.format(name))

    def clean_agreement(self):
        value = self.cleaned_data['agreement']
        if not value:
            raise forms.ValidationError(
                "You must agree with this statement to submit a prize.")
        return value

    def clean(self):
        if not self.cleaned_data['startrun']:
            self.cleaned_data['startrun'] = self.cleaned_data.get(
                'endrun', None)
        if not self.cleaned_data['endrun']:
            self.cleaned_data['endrun'] = self.cleaned_data.get(
                'startrun', None)
        if self.cleaned_data['startrun'] and self.cleaned_data['startrun'].starttime > self.cleaned_data['endrun'].starttime:
            self.errors['startrun'] = "Start run must be before the end run"
            self.errors['endrun'] = "Start run must be before the end run"
            raise forms.ValidationError(
                "Error, Start run must be before the end run")
        return self.cleaned_data

    def save(self, event, handler=None):
        provider = ''
        if handler and handler.username != handler.email:
            provider = handler.username
        prize = models.Prize.objects.create(
            event=event,
            name=self.cleaned_data['name'],
            description=self.cleaned_data['description'],
            maxwinners=self.cleaned_data['maxwinners'],
            extrainfo=self.cleaned_data['extrainfo'],
            estimatedvalue=self.cleaned_data['estimatedvalue'],
            minimumbid=5,
            maximumbid=5,
            image=self.cleaned_data['imageurl'],
            handler=handler,
            provider=provider,
            creator=self.cleaned_data['creatorname'],
            creatoremail=self.cleaned_data['creatoremail'],
            creatorwebsite=self.cleaned_data['creatorwebsite'],
            startrun=self.cleaned_data['startrun'],
            endrun=self.cleaned_data['endrun'])
        prize.save()
        return prize
コード例 #9
0
class PrizeSearchForm(forms.Form):
    feed = forms.ChoiceField(required=False, initial='upcomming', choices=(
        ('all', 'All'), ('unwon', 'Not Drawn'), ('won', 'Drawn'), ('current', 'Current'), ('future', 'Future')), label='Type')
    q = forms.CharField(required=False, initial=None,
                        max_length=255, label='Search')
コード例 #10
0
class RunSearchForm(forms.Form):
    feed = forms.ChoiceField(required=False, initial='current', choices=(
        ('all', 'All'), ('current', 'Current'), ('future', 'Future')), label='Type')
    q = forms.CharField(required=False, initial=None,
                        max_length=255, label='Search')
コード例 #11
0
class DonationSearchForm(forms.Form):
    feed = forms.ChoiceField(required=False, initial='recent', choices=(
        ('all', 'All'), ('recent', 'Recent')), label='Filter')
    q = forms.CharField(required=False, initial=None,
                        max_length=255, label='Search')
コード例 #12
0
class DonorSearchForm(forms.Form):
    q = forms.CharField(required=False, initial=None,
                        max_length=255, label='Search')