コード例 #1
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'}))
コード例 #2
0
class PrizeTicketForm(forms.Form):
    prize = forms.fields.IntegerField(
        label="", required=False, widget=tracker.widgets.MegaFilterWidget(model="prize"))
    amount = forms.DecimalField(decimal_places=2, max_digits=20, required=False, validators=[
                                positive, nonzero], widget=tracker.widgets.NumberInput(attrs={'class': 'cprizeamount', 'step': '0.01'}))

    def clean_prize(self):
        try:
            prize = self.cleaned_data['prize']
            if not prize:
                prize = None
            else:
                prize = models.Prize.objects.get(id=prize)
                if prize.maxed_winners():
                    raise forms.ValidationError(
                        "This prize has already been drawn.")
        except Exception as e:
            raise forms.ValidationError("Prize does not exist.")
        return prize

    def clean(self):
        if self.cleaned_data['amount'] and (not ('prize' in self.cleaned_data) or not self.cleaned_data['prize']):
            raise forms.ValidationError(_("Error, did not specify a prize"))
        if self.cleaned_data['prize'] and not self.cleaned_data['amount']:
            raise forms.ValidationError(_("Error, did not specify an amount"))
        return self.cleaned_data
コード例 #3
0
class DonationBidForm(forms.Form):
    bid = forms.fields.IntegerField(
        label="", required=False, widget=tracker.widgets.MegaFilterWidget(model="bidtarget"))
    customoptionname = forms.fields.CharField(max_length=models.Bid._meta.get_field(
        'name').max_length, label='New Option Name:', required=False)
    amount = forms.DecimalField(decimal_places=2, max_digits=20, required=False, validators=[
                                positive, nonzero], widget=tracker.widgets.NumberInput(attrs={'class': 'cdonationbidamount', 'step': '0.01'}))

    def clean_bid(self):
        try:
            bid = self.cleaned_data['bid']
            if not bid:
                bid = None
            else:
                bid = models.Bid.objects.get(id=bid)
            if bid.state == 'CLOSED':
                raise forms.ValidationError(
                    "This bid not open for new donations anymore.")
        except Exception as e:
            raise forms.ValidationError("Bid does not exist.")
        return bid

    def clean_amount(self):
        try:
            amount = self.cleaned_data['amount']
            if not amount:
                amount = None
            else:
                amount = Decimal(amount)
        except Exception as e:
            raise forms.ValidationError('Could not parse amount.')
        return amount

    def clean_customoptionname(self):
        return self.cleaned_data['customoptionname'].strip()

    def clean(self):
        if 'amount' not in self.cleaned_data:
            self.cleaned_data['amount'] = None
        if 'bid' not in self.cleaned_data:
            self.cleaned_data['bid'] = None
        if self.cleaned_data['amount'] and not self.cleaned_data['bid']:
            raise forms.ValidationError(_("Error, did not specify a bid"))
        if self.cleaned_data['bid'] and not self.cleaned_data['amount']:
            raise forms.ValidationError(_("Error, did not specify an amount"))
        if self.cleaned_data['bid']:
            if self.cleaned_data['bid'].allowuseroptions:
                if not self.cleaned_data['customoptionname']:
                    raise forms.ValidationError(
                        _('Error, did not specify a name for the custom option.'))
                elif self.cleaned_data['amount'] < Decimal('1.00'):
                    raise forms.ValidationError(
                        _('Error, you must bid at least one dollar for a custom bid.'))
        return self.cleaned_data
コード例 #4
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')
コード例 #5
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")
コード例 #6
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