def __init__(self, *args, **kwargs): """ Add any custom fields that are defined to the form """ super(PublicTicketForm, self).__init__(*args, **kwargs) for field in CustomField.objects.filter(staff_only=False): instanceargs = { 'label': field.label, 'help_text': field.help_text, 'required': field.required, } self.customfield_to_field(field, instanceargs) # add the captcha field here because it has to be the last field self.fields['captcha'] = CustomCatpchaField(label=_('Type the code below'))
class SubmitContactForm(forms.Form): first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100, required=False) address = forms.CharField(max_length=50, required=False) city = forms.CharField(max_length=50, required=False) state = forms.CharField(max_length=50, required=False) zipcode = forms.CharField(max_length=10, required=False) country = CountrySelectField(required=False) phone = forms.CharField(max_length=20, required=False) email = EmailVerificationField(label=_("Email")) url = forms.URLField(label=_('URL'), max_length=200, required=False) message = forms.CharField(widget=forms.Textarea) captcha = CustomCatpchaField(label=_('Type the code below'))
def __init__(self, *args, **kwargs): super(CreatorForm, self).__init__(*args, **kwargs) self.fields['captcha'] = CustomCatpchaField( label=_('Type the code below')) for k in self.fields.keys(): self.fields[k].widget.attrs['class'] = 'form-control'
class ResumeForm(TendenciBaseForm): description = forms.CharField(required=False, widget=TinyMCE( attrs={'style': 'width:100%'}, mce_attrs={ 'storme_app_label': Resume._meta.app_label, 'storme_model': Resume._meta.model_name.lower() })) resume_url = forms.CharField( label=_('Resume URL'), help_text=_("Link to an external resume (eg. LinkedIn)"), required=False) is_agency = forms.BooleanField( label=_('Agency'), help_text=_("Are you an agency posting this resume?"), required=False) requested_duration = forms.ChoiceField( label=_('Duration'), choices=( ('30', _('30 Days')), ('60', _('60 Days')), ('90', _('90 Days')), ), help_text=_("Amount of days you would like your resume to stay up."), required=False) captcha = CustomCatpchaField(label=_('Type the code below')) contact_email = EmailVerificationField(label=_("Email"), required=False) contact_country = CountrySelectField(label=_("Country"), required=False) contact_address = forms.CharField(label=_("Address"), required=False) contact_address2 = forms.CharField(label=_("Address2"), required=False) contact_city = forms.CharField(label=_("City"), required=False) contact_zip_code = forms.CharField(label=_("Zip code"), required=False) contact_country = forms.CharField(label=_("Country"), required=False) contact_phone = forms.CharField(label=_("Phone"), required=False) contact_phone2 = forms.CharField(label=_("Phone2"), required=False) contact_fax = forms.CharField(label=_("Fax"), required=False) contact_website = forms.CharField(label=_("Website"), required=False) activation_dt = forms.SplitDateTimeField(label=_('Activation Date/Time'), initial=datetime.now()) expiration_dt = forms.SplitDateTimeField(label=_('Expriation Date/Time'), initial=(datetime.now() + timedelta(days=30))) syndicate = forms.BooleanField(label=_('Include in RSS Feed'), required=False, initial=True) status_detail = forms.ChoiceField(choices=( ('active', _('Active')), ('inactive', _('Inactive')), ('pending', _('Pending')), )) class Meta: model = Resume fields = ( 'title', 'slug', 'description', 'resume_url', 'resume_file', 'industry', 'location', 'skills', 'experience', 'awards', 'education', 'is_agency', 'requested_duration', 'tags', 'first_name', 'last_name', 'contact_address', 'contact_address2', 'contact_city', 'contact_state', 'contact_zip_code', 'contact_country', 'contact_phone', 'contact_phone2', 'contact_fax', 'contact_email', 'contact_website', 'captcha', 'allow_anonymous_view', 'user_perms', 'group_perms', 'activation_dt', 'expiration_dt', 'syndicate', 'status_detail', ) fieldsets = [(_('Resume Information'), { 'fields': [ 'title', 'slug', 'description', 'resume_url', 'resume_file', 'industry', 'location', 'skills', 'experience', 'awards', 'education', 'tags', 'requested_duration', 'is_agency', ], 'legend': '' }), (_('Contact'), { 'fields': [ 'first_name', 'last_name', 'contact_address', 'contact_address2', 'contact_city', 'contact_state', 'contact_zip_code', 'contact_country', 'contact_phone', 'contact_phone2', 'contact_fax', 'contact_email', 'contact_website', ], 'classes': ['contact'], }), (_('Security Code'), { 'fields': [ 'captcha', ], 'classes': ['captcha'], }), (_('Permissions'), { 'fields': [ 'allow_anonymous_view', 'user_perms', 'member_perms', 'group_perms', ], 'classes': ['permissions'], }), (_('Administrator Only'), { 'fields': [ 'activation_dt', 'expiration_dt', 'syndicate', 'status', 'status_detail' ], 'classes': ['admin-only'], })] def __init__(self, *args, **kwargs): super(ResumeForm, self).__init__(*args, **kwargs) self.fields['first_name'].required = True self.fields['last_name'].required = True if self.instance.pk: self.fields['description'].widget.mce_attrs[ 'app_instance_id'] = self.instance.pk else: self.fields['description'].widget.mce_attrs['app_instance_id'] = 0 # adjust fields depending on user status fields_to_pop = [] if not self.user.is_authenticated: fields_to_pop += [ 'allow_anonymous_view', 'user_perms', 'member_perms', 'group_perms', 'activation_dt', 'expiration_dt', 'syndicate', 'status_detail' ] else: fields_to_pop += ['captcha'] if not self.user.profile.is_superuser: fields_to_pop += [ 'allow_anonymous_view', 'user_perms', 'member_perms', 'group_perms', 'activation_dt', 'expiration_dt', 'syndicate', 'status_detail' ] # Populate contact info for non-superuser self.fields['first_name'].initial = self.user.first_name self.fields['last_name'].initial = self.user.last_name self.fields['contact_address'].initial = self.user.profile.address self.fields[ 'contact_address2'].initial = self.user.profile.address2 self.fields['contact_city'].initial = self.user.profile.city self.fields['contact_state'].initial = self.user.profile.state self.fields['contact_zip_code'].initial = self.user.profile.zipcode self.fields['contact_country'].initial = self.user.profile.country self.fields['contact_phone'].initial = self.user.profile.phone self.fields['contact_phone2'].initial = self.user.profile.phone2 self.fields['contact_fax'].initial = self.user.profile.fax self.fields['contact_email'].initial = self.user.email self.fields['contact_website'].initial = self.user.profile.url for f in list(set(fields_to_pop)): if f in self.fields: self.fields.pop(f) def clean_syndicate(self): """ clean method for syndicate added due to the update done on the field BooleanField -> NullBooleanField NOTE: BooleanField is converted to NullBooleanField because some Boolean data has value of None than False. This was updated on Django 1.6. BooleanField cannot have a value of None. """ data = self.cleaned_data.get('syndicate', False) if data: return True else: return False def clean_resume_file(self): resume = self.cleaned_data['resume_file'] if resume: extension = splitext(resume.name)[1] # check the extension if extension.lower() not in ALLOWED_FILE_EXT: raise forms.ValidationError( _('The file must be of doc, docx, pdf, or rtf format.')) return resume def clean(self): cleaned_data = super(ResumeForm, self).clean() print(self.errors) return cleaned_data
def __init__(self, form, user, *args, **kwargs): """ Dynamically add each of the form fields for the given form model instance and its related field model instances. """ self.user = user self.form = form self.form_fields = form.fields.visible().order_by('position') self.auto_fields = form.fields.auto_fields().order_by('position') super(FormForForm, self).__init__(*args, **kwargs) def add_fields(form, form_fields): for field in form_fields: field_key = self.field_key(field) if "/" in field.field_type: field_class, field_widget = field.field_type.split("/") else: field_class, field_widget = field.field_type, None if field.field_type == 'EmailVerificationField': one_email = get_setting('module', 'forms', 'one_email') if one_email: field_class = forms.EmailField else: field_class = EmailVerificationField elif field.field_type == 'BooleanField' and len( field.choices) > 0: field_class = forms.MultipleChoiceField field_widget = 'django.forms.CheckboxSelectMultiple' elif field.field_type == 'CountryField': field_class = CountrySelectField elif field.field_type == 'StateProvinceField': field_class = getattr(forms, 'ChoiceField') else: field_class = getattr(forms, field_class) field_args = { "label": mark_safe(field.label), "required": field.required } arg_names = field_class.__init__.__code__.co_varnames if "max_length" in arg_names: field_args["max_length"] = FIELD_MAX_LENGTH if "choices" in arg_names and field.field_type != 'CountryField': field_args["choices"] = field.get_choices() #field_args["choices"] = zip(choices, choices) if field_class == "BooleanField": default = field.default.lower() if default == "checked" or default == "true" or \ default == "on" or default == "1": default = True else: default = False field.default = default field_args["initial"] = field.default if field_widget is not None: module, widget = field_widget.rsplit(".", 1) # django.forms.extras moved to django.forms.widgets since Django 1.9 if module == 'django.forms.extras': module = 'django.forms.widgets' field_args["widget"] = getattr(import_module(module), widget) if field.field_function == 'EmailFirstName': field_args["max_length"] = FIELD_FNAME_LENGTH elif field.field_function == 'EmailLastName': field_args["max_length"] = FIELD_LNAME_LENGTH elif field.field_function == 'EmailFullName': field_args["max_length"] = FIELD_NAME_LENGTH elif field.field_function == 'EmailPhoneNumber': field_args["max_length"] = FIELD_PHONE_LENGTH elif field.field_type == 'FileField': field_args["validators"] = [FileValidator()] form.fields[field_key] = field_class(**field_args) if not field_class == EmailVerificationField: form.fields[field_key].widget.attrs['title'] = field.label form.fields[field_key].widget.attrs[ 'class'] = 'formforform-field' else: form.fields[field_key].widget.widgets[0].attrs[ 'class'] += ' formforform-field' form.fields[field_key].widget.widgets[1].attrs[ 'class'] += ' formforform-field' widget_name = form.fields[ field_key].widget.__class__.__name__.lower() if widget_name == 'selectdatewidget': form.fields[field_key].widget.years = list( range(1920, THIS_YEAR + 10)) if widget_name in ('dateinput', 'selectdatewidget', 'datetimeinput'): form.fields[field_key].initial = datetime.now() def add_pricing_fields(form, formforform): # include pricing options if any if (formforform.custom_payment or formforform.recurring_payment ) and formforform.pricing_set.all(): #currency_symbol = get_setting('site', 'global', 'currencysymbol') pricing_options = [] for pricing in formforform.pricing_set.all(): if pricing.price is None: pricing_options.append(( pricing.pk, mark_safe( '<input type="text" class="custom-price" name="custom_price_%s" value="%s"/> <strong>%s</strong><br>%s' % (pricing.pk, form.data.get( 'custom_price_%s' % pricing.pk, str()), pricing.label, pricing.description)))) else: if formforform.recurring_payment: pricing_options.append( (pricing.pk, mark_safe( '<strong>%s per %s %s - %s</strong><br>%s' % (tcurrency(pricing.price), pricing.billing_frequency, pricing.billing_period, pricing.label, pricing.description)))) else: pricing_options.append( (pricing.pk, mark_safe( '<strong>%s %s</strong><br>%s' % (tcurrency(pricing.price), pricing.label, pricing.description)))) form.fields['pricing_option'] = forms.ChoiceField( label=formforform.pricing_name or _('Pricing'), choices=pricing_options, widget=forms.RadioSelect(attrs={'class': 'pricing-field'})) form.fields['payment_option'] = forms.ModelChoiceField( label=_('Payment Method'), empty_label=None, queryset=formforform.payment_methods.all(), widget=forms.RadioSelect(attrs={'class': 'payment-field'}), initial=1, ) if self.form.pricing_position < self.form.fields_position: add_pricing_fields(self, self.form) add_fields(self, self.form_fields) else: add_fields(self, self.form_fields) add_pricing_fields(self, self.form) if get_setting( 'site', 'global', 'captcha' ) and not user.is_authenticated: # add captcha if not logged in self.fields['captcha'] = CustomCatpchaField( label=_('Type the code below')) self.add_form_control_class()
class RequestForm(forms.ModelForm): captcha = CustomCatpchaField() class Meta: model = Request fields = "__all__"
class JobForm(TendenciBaseForm): description = forms.CharField( required=False, widget=TinyMCE( attrs={'style': 'width:100%'}, mce_attrs={'storme_app_label': Job._meta.app_label, 'storme_model': Job._meta.model_name.lower()} ) ) captcha = CustomCatpchaField(label=_('Type the code below')) start_dt = forms.SplitDateTimeField( required=False, label=_('Position starts on:'), initial=datetime.now()) activation_dt = forms.SplitDateTimeField( label=_('Activation Date/Time'), initial=datetime.now()) post_dt = forms.SplitDateTimeField( label=_('Post Date/Time'), initial=datetime.now()) expiration_dt = forms.SplitDateTimeField( label=_('Expiration Date/Time'), initial=datetime.now()) syndicate = forms.BooleanField(label=_('Include in RSS Feed'), required=False, initial=True) status_detail = forms.ChoiceField( choices=(('active', _('Active')), ('inactive', _('Inactive')), ('pending', _('Pending')),)) list_type = forms.ChoiceField(initial='regular', choices=(('regular', _('Regular')), ('premium', _('Premium')),)) payment_method = forms.ChoiceField(error_messages={'required': _('Please select a payment method.')}) contact_email = EmailVerificationField(label=_("Contact email"), required=False) contact_country = CountrySelectField(label=_("Contact country"), required=False) group = forms.ModelChoiceField(queryset=Group.objects.filter(status=True, status_detail="active"), required=True, empty_label=None) pricing = forms.ModelChoiceField(queryset=JobPricing.objects.filter(status=True).order_by('duration'), **request_duration_defaults) cat = forms.ModelChoiceField(label=_("Category"), queryset=JobCategory.objects.filter(parent=None), empty_label="-----------", required=False) sub_cat = forms.ModelChoiceField(label=_("Subcategory"), queryset=JobCategory.objects.none(), empty_label=_("Please choose a category first"), required=False) class Meta: model = Job fields = ( 'title', 'slug', 'description', 'group', 'code', 'location', 'skills', 'experience', 'education', 'level', 'period', 'is_agency', 'contact_method', 'position_reports_to', 'salary_from', 'salary_to', 'computer_skills', 'tags', 'pricing', 'list_type', 'start_dt', 'activation_dt', 'post_dt', 'expiration_dt', 'job_url', 'entity', 'contact_company', 'contact_name', 'contact_address', 'contact_address2', 'contact_city', 'contact_state', 'contact_zip_code', 'contact_country', 'contact_phone', 'contact_fax', 'contact_email', 'contact_website', 'tags', 'allow_anonymous_view', 'syndicate', 'status_detail', 'payment_method', 'cat', 'sub_cat' ) fieldsets = [ (_('Job Information'), { 'fields': [ 'title', 'slug', 'description', 'group', 'job_url', 'start_dt', 'code', 'location', 'skills', 'computer_skills', 'experience', 'education', 'level', 'period', 'contact_method', 'position_reports_to', 'salary_from', 'salary_to', 'is_agency', 'tags', 'pricing', 'activation_dt', 'expiration_dt', 'post_dt', 'entity' ], 'legend': '' }), (_('Payment'), { 'fields': ['list_type', 'payment_method'], 'classes': ['payment_method'], }), (_('Contact'), { 'fields': [ 'contact_company', 'contact_name', 'contact_address', 'contact_address2', 'contact_city', 'contact_state', 'contact_zip_code', 'contact_country', 'contact_phone', 'contact_fax', 'contact_email', 'contact_website' ], 'classes': ['contact'], }), (_('Security Code'), { 'fields': ['captcha'], 'classes': ['captcha'], }), (_('Permissions'), { 'fields': [ 'allow_anonymous_view', 'user_perms', 'member_perms', 'group_perms', ], 'classes': ['permissions'], }), (_('Category'), { 'fields': ['cat', 'sub_cat' ], 'classes': ['boxy-grey job-category'], }), (_('Administrator Only'), { 'fields': ['syndicate', 'status_detail'], 'classes': ['admin-only'], })] def __init__(self, *args, **kwargs): if hasattr(self, 'user'): kwargs.update({'user': self.user}) super(JobForm, self).__init__(*args, **kwargs) if self.instance.pk: self.fields['description'].widget.mce_attrs['app_instance_id'] = self.instance.pk #self.fields['pricing'].initial = JobPricing.objects.filter(duration=self.instance.requested_duration)[0] if self.user.profile.is_superuser: self.fields['status_detail'].choices = STATUS_DETAIL_CHOICES else: self.fields['description'].widget.mce_attrs['app_instance_id'] = 0 self.fields['group'].initial = Group.objects.get_initial_group_id() # cat and sub_cat if self.user.profile.is_superuser: self.fields['sub_cat'].help_text = mark_safe('<a href="{0}">{1}</a>'.format( reverse('admin:jobs_category_changelist'), _('Manage Categories'),)) if self.instance and self.instance.pk: self.fields['sub_cat'].queryset = JobCategory.objects.filter( parent=self.instance.cat) if args: post_data = args[0] else: post_data = None if post_data: cat = post_data.get('cat', '0') if cat and cat != '0' and cat != u'': cat = JobCategory.objects.get(pk=int(cat)) self.fields['sub_cat'].queryset = JobCategory.objects.filter(parent=cat) self.fields['pricing'].choices = pricing_choices(self.user) if 'payment_method' in self.fields: choices=get_payment_method_choices(self.user) self.fields['payment_method'].widget = forms.RadioSelect(choices=choices) self.fields['payment_method'].choices = choices #self.fields['payment_method'].widget = forms.RadioSelect(choices=choices) if choices and len(choices) == 1: self.fields['payment_method'].initial = choices[0][0] # adjust fields depending on user status fields_to_pop = [] if not self.user.is_authenticated: fields_to_pop += [ 'entity', 'allow_anonymous_view', 'user_perms', 'group_perms', 'member_perms', 'post_dt', 'activation_dt', 'expiration_dt', 'syndicate', 'status_detail' ] else: fields_to_pop += [ 'captcha' ] if not self.user.profile.is_superuser: fields_to_pop += [ 'slug', 'entity', 'group', 'allow_anonymous_view', 'user_perms', 'member_perms', 'group_perms', 'post_dt', 'activation_dt', 'expiration_dt', 'syndicate', 'status_detail' ] for f in list(set(fields_to_pop)): if f in self.fields: self.fields.pop(f) def clean_syndicate(self): """ clean method for syndicate added due to the update done on the field BooleanField -> NullBooleanField NOTE: BooleanField is converted to NullBooleanField because some Boolean data has value of None than False. This was updated on Django 1.6. BooleanField cannot have a value of None. """ data = self.cleaned_data.get('syndicate', False) if data: return True else: return False def save(self, *args, **kwargs): """ Assigns the requested_duration of a job based on the chosen pricing. """ job = super(JobForm, self).save(commit=False) if 'pricing' in self.cleaned_data: job.requested_duration = self.cleaned_data['pricing'].duration if kwargs['commit']: job.save() return job
def form_detail(request, slug, template="forms/form_detail.html"): """ Display a built form and handle submission. """ published = Form.objects.published(for_user=request.user) form = get_object_or_404(published, slug=slug) if not has_view_perm(request.user, 'forms.view_form', form): raise Http403 # If form has a recurring payment, make sure the user is logged in if form.recurring_payment: [email_field] = form.fields.filter( field_type__iexact='EmailVerificationField')[:1] or [None] if request.user.is_anonymous and not email_field: # anonymous user - if we don't have the email field, redirect to login response = redirect('auth_login') response['Location'] += '?next=%s' % form.get_absolute_url() return response if request.user.is_superuser and not email_field: messages.add_message( request, messages.WARNING, 'Please edit the form to include an email field ' + 'as it is required for setting up a recurring ' + 'payment for anonymous users.') if form.custom_payment and not form.recurring_payment: billing_form = BillingForm(request.POST or None) if request.user.is_authenticated: billing_form.initial = { 'first_name': request.user.first_name, 'last_name': request.user.last_name, 'email': request.user.email } else: billing_form = None form_for_form = FormForForm(form, request.user, request.session, request.POST or None, request.FILES or None) if get_setting('site', 'global', 'captcha'): # add captcha if billing_form: # append the captcha to the end of the billing form captcha_field = CustomCatpchaField(label=_('Type the code below')) if 'captcha' in form_for_form.fields: form_for_form.fields.pop('captcha') billing_form.fields['captcha'] = captcha_field for field in form_for_form.fields: field_default = request.GET.get(field, None) if field_default: form_for_form.fields[field].initial = field_default if request.method == "POST": if form_for_form.is_valid() and (not billing_form or billing_form.is_valid()): entry = form_for_form.save() entry.entry_path = request.POST.get("entry_path", "") if request.user.is_anonymous: entry.creator = entry.check_and_create_user() else: entry.creator = request.user entry.save() entry.set_group_subscribers() # Email subject = generate_email_subject(form, entry) email_headers = {} # content type specified below if form.email_from: email_headers.update({'Reply-To': form.email_from}) # Email to submitter # fields aren't included in submitter body to prevent spam submitter_body = generate_submitter_email_body( entry, form_for_form) email_from = form.email_from or settings.DEFAULT_FROM_EMAIL email_to = form_for_form.email_to() is_spam = Email.is_blocked(email_to) if is_spam: # log the spam description = "Email \"{0}\" blocked because it is listed in email_blocks.".format( email_to) EventLog.objects.log(instance=form, description=description) if form.completion_url: return HttpResponseRedirect(form.completion_url) return redirect("form_sent", form.slug) email = Email() email.subject = subject email.reply_to = form.email_from if email_to and form.send_email and form.email_text: # Send message to the person who submitted the form. email.recipient = email_to email.body = submitter_body email.send(fail_silently=getattr(settings, 'EMAIL_FAIL_SILENTLY', True)) # log an event EventLog.objects.log( instance=form, description='Confirmation email sent to {}'.format( email_to)) # Email copies to admin admin_body = generate_admin_email_body(entry, form_for_form, user=request.user) email_from = email_to or email_from # Send from the email entered. email_headers = {} # Reset the email_headers email_headers.update({'Reply-To': email_from}) email_copies = [ e.strip() for e in form.email_copies.split(',') if e.strip() ] subject = subject.encode(errors='ignore') email_recipients = entry.get_function_email_recipients() # reply_to of admin emails goes to submitter email.reply_to = email_to if email_copies or email_recipients: # prepare attachments attachments = [] # Commenting out the attachment block to not add attachments to the email for the reason below: # According to SES message quotas https://docs.aws.amazon.com/ses/latest/DeveloperGuide/quotas.html, # the maximum message size (including attachments) is 10 MB per message (after base64 encoding) # which means the actual size should be less than 7.5 MB or so because text after encoded with the BASE64 # algorithm increases its size by 1/3. But the allowed upload size is much larger than 7.5 MB. # try: # for f in form_for_form.files.values(): # f.seek(0) # attachments.append((f.name, f.read())) # except ValueError: # attachments = [] # for field_entry in entry.fields.all(): # if field_entry.field.field_type == 'FileField': # try: # f = default_storage.open(field_entry.value) # except IOError: # pass # else: # f.seek(0) # attachments.append((f.name.split('/')[-1], f.read())) fail_silently = getattr(settings, 'EMAIL_FAIL_SILENTLY', True) # Send message to the email addresses listed in the copies if email_copies: email.body = admin_body email.recipient = email_copies # if request.user.is_anonymous or not request.user.is_active: # email.content_type = 'text' email.send(fail_silently=fail_silently, attachments=attachments) # Email copies to recipient list indicated in the form if email_recipients: email.body = admin_body email.recipient = email_recipients email.send(fail_silently=fail_silently, attachments=attachments) # payment redirect if (form.custom_payment or form.recurring_payment) and entry.pricing: # get the pricing's price, custom or otherwise price = entry.pricing.price or form_for_form.cleaned_data.get( 'custom_price') if form.recurring_payment: if request.user.is_anonymous: rp_user = entry.creator else: rp_user = request.user billing_start_dt = datetime.datetime.now() trial_period_start_dt = None trial_period_end_dt = None if entry.pricing.has_trial_period: trial_period_start_dt = datetime.datetime.now() trial_period_end_dt = trial_period_start_dt + datetime.timedelta( 1) billing_start_dt = trial_period_end_dt # Create recurring payment rp = RecurringPayment( user=rp_user, description=form.title, billing_period=entry.pricing.billing_period, billing_start_dt=billing_start_dt, num_days=entry.pricing.num_days, due_sore=entry.pricing.due_sore, payment_amount=price, taxable=entry.pricing.taxable, tax_rate=entry.pricing.tax_rate, has_trial_period=entry.pricing.has_trial_period, trial_period_start_dt=trial_period_start_dt, trial_period_end_dt=trial_period_end_dt, trial_amount=entry.pricing.trial_amount, creator=rp_user, creator_username=rp_user.username, owner=rp_user, owner_username=rp_user.username, ) rp.save() if rp.platform == 'authorizenet': rp.add_customer_profile() # redirect to recurring payments messages.add_message(request, messages.SUCCESS, _('Successful transaction.')) return redirect('recurring_payment.view_account', rp.id, rp.guid) else: # create the invoice invoice = make_invoice_for_entry(entry, custom_price=price) update_invoice_for_entry(invoice, billing_form) # log an event for invoice add EventLog.objects.log(instance=form) # redirect to online payment if invoice.balance > 0: if (entry.payment_method.machine_name ).lower() == 'credit-card': return redirect('payment.pay_online', invoice.id, invoice.guid) # redirect to invoice page return redirect('invoice.view', invoice.id, invoice.guid) # default redirect if form.completion_url: completion_url = form.completion_url.strip().replace( '[entry_id]', str(entry.id)) return HttpResponseRedirect(completion_url) return redirect("form_sent", form.slug) # set form's template to forms/base.html if no template or template doesn't exist if not form.template or not template_exists(form.template): form.template = "forms/base.html" context = { "form": form, 'billing_form': billing_form, "form_for_form": form_for_form, 'form_template': form.template, } return render_to_resp(request=request, template_name=template, context=context)
class RegistrationForm(forms.Form): """ Registration form. Focuses on non-registrant specific details. """ amount_for_admin = forms.DecimalField(decimal_places=2, required=False) discount = forms.CharField(label=_('Discount Code'), required=False) captcha = CustomCatpchaField(label=_('Type the code below')) payment_method = forms.ModelChoiceField(empty_label=None, required=True, queryset=PaymentMethod.objects.none(), widget=forms.RadioSelect, initial=1) def __init__(self, event, user, *args, **kwargs): """ event: instance of Event model user: request.user reg_count: used for discount validation (discounts have usage limits) """ self.event = event self.user = user self.reg_count = kwargs.pop('reg_count', 0) super(RegistrationForm, self).__init__(*args, **kwargs) # no need for captcha if logged in if user.is_authenticated: self.fields.pop('captcha') # admin only price override field if not user.profile.is_superuser: self.fields.pop('amount_for_admin') reg_conf = event.registration_configuration if reg_conf.can_pay_online: payment_methods = reg_conf.payment_method.all() else: payment_methods = reg_conf.payment_method.exclude( machine_name='credit card').order_by('pk') self.fields['payment_method'].queryset = payment_methods def get_user(self): return self.user def get_event(self): return self.event def clean_discount(self): """ Returns the discount instance if it exists for a given code. Returns none if the code is blank. """ code = self.cleaned_data['discount'] if code: try: discount = Discount.objects.get(discount_code=self.cleaned_data['discount']) if discount.available_for(self.reg_count): return discount else: raise forms.ValidationError(_("Discount Code cannot be used for %s people." % self.reg_count)) except Discount.objects.DoesNotExist: raise forms.ValidationError(_("This is not a valid Discount Code!")) return code
class RegistrationCustomForm(RegistrationForm): first_name = forms.CharField( max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) last_name = forms.CharField( max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) company = forms.CharField(max_length=100, widget=forms.TextInput(attrs={ 'size': '40', 'class': 'form-control' }), required=False) phone = forms.CharField( max_length=50, required=False, widget=forms.TextInput(attrs={'class': 'form-control'})) address = forms.CharField(max_length=150, widget=forms.TextInput(attrs={ 'size': '40', 'class': 'form-control' }), required=False) city = forms.CharField( max_length=50, required=False, widget=forms.TextInput(attrs={'class': 'form-control'})) state = forms.CharField(max_length=50, widget=forms.TextInput(attrs={ 'size': '10', 'class': 'form-control' }), required=False) country = forms.CharField( max_length=50, required=False, widget=forms.TextInput(attrs={'class': 'form-control'})) zipcode = forms.CharField( max_length=50, required=False, widget=forms.TextInput(attrs={'class': 'form-control'})) captcha = CustomCatpchaField( label=_('Type the letters you see in the box'), widget=CaptchaTextInput(attrs={'class': 'form-control'})) allow_same_email = None similar_email_found = False def __init__(self, *args, **kwargs): self.allow_same_email = kwargs.pop('allow_same_email', False) super(RegistrationCustomForm, self).__init__(*args, **kwargs) def clean_password1(self): password1 = self.cleaned_data.get('password1') password_regex = get_setting('module', 'users', 'password_requirements_regex') password_requirements = get_setting('module', 'users', 'password_text') if password_regex: if not re.match(password_regex, password1): raise forms.ValidationError( mark_safe( _("The password does not meet the requirements: %(p)s" % {'p': password_requirements}))) return password1 def clean(self): cleaned_data = super(RegistrationCustomForm, self).clean() if self._errors: return user = User.objects.filter(email=cleaned_data['email']) if user and not self.allow_same_email: self.similar_email_found = True raise forms.ValidationError(_("Similar emails found")) return cleaned_data def save(self, profile_callback=None, event=None): # #new_user = RegistrationProfile.objects.create_inactive_user(username=self.cleaned_data['username'], # password=self.cleaned_data['password1'], # create inactive user email=self.cleaned_data['email']) new_user = User.objects.create_user(self.cleaned_data['username'], self.cleaned_data['email'], self.cleaned_data['password1']) new_user.first_name = self.cleaned_data['first_name'] new_user.last_name = self.cleaned_data['last_name'] new_user.is_active = False new_user.save() # create registration profile registration_profile = RegistrationProfile.objects.create_profile( new_user) send_registration_activation_email(new_user, registration_profile, event=event) new_profile = Profile( user=new_user, company=self.cleaned_data['company'], phone=self.cleaned_data['phone'], address=self.cleaned_data['address'], city=self.cleaned_data['city'], state=self.cleaned_data['state'], country=self.cleaned_data['country'], zipcode=self.cleaned_data['zipcode'], ) user_hide_default = get_setting('module', 'users', 'usershidedefault') if user_hide_default: new_profile.hide_in_search = 1 new_profile.hide_address = 1 new_profile.hide_email = 1 new_profile.hide_phone = 1 new_profile.creator = new_user new_profile.creator_username = new_user.username new_profile.owner = new_user new_profile.owner_username = new_user.username new_profile.save() create_salesforce_contact(new_profile) # Returns sf_id return new_user
class MakePaymentForm(forms.ModelForm): captcha = CustomCatpchaField(label=_('Type the code below')) # TODO: Make check-paid an admin only option payment_amount = PriceField(max_digits=10, decimal_places=2) payment_method = forms.CharField(widget=forms.RadioSelect(choices=(('cc', _('Make Online Payment')),)), initial='cc',) company = forms.CharField(max_length=50, required=False, widget=forms.TextInput(attrs={'size':'30'})) address = forms.CharField(max_length=100, required=False, widget=forms.TextInput(attrs={'size':'35'})) state = forms.CharField(max_length=50, required=False, widget=forms.TextInput(attrs={'size':'5'})) zip_code = forms.CharField(max_length=20, required=False, widget=forms.TextInput(attrs={'size':'10'})) reference_number = forms.CharField(max_length=20, required=False, widget=forms.TextInput(attrs={'size':'15'})) referral_source = forms.CharField(max_length=200, required=False, widget=forms.TextInput(attrs={'size':'40'})) email = EmailVerificationField(label=_("Email"), help_text=_('A valid e-mail address, please.')) email_receipt = forms.BooleanField(initial=True) country = forms.ChoiceField(label=_('Country'), choices=(('', '-----------'),) + tuple(COUNTRIES)) class Meta: model = MakePayment fields = ('payment_amount', 'payment_method', 'first_name', 'last_name', 'company', 'address', 'address2', 'city', 'state', 'zip_code', 'country', 'phone', 'email', 'email_receipt', 'reference_number', 'referral_source', 'comments', 'captcha', ) def __init__(self, user, *args, **kwargs): super(MakePaymentForm, self).__init__(*args, **kwargs) self.initial['country'] = get_setting('site', 'global', 'defaultcountry') self.fields['reference_number'].label = get_setting('module', 'make_payment', 'referencenumberlabel') or _('Reference #') # populate the user fields if user and user.id: if 'captcha' in self.fields: self.fields.pop('captcha') self.fields['first_name'].initial = user.first_name self.fields['last_name'].initial = user.last_name self.fields['email'].initial = user.email try: profile = user.profile if profile: self.fields['company'].initial = profile.company self.fields['address'].initial = profile.address self.fields['address2'].initial = profile.address2 self.fields['city'].initial = profile.city self.fields['state'].initial = profile.state self.fields['zip_code'].initial = profile.zipcode self.fields['country'].initial = profile.country self.fields['phone'].initial = profile.phone except: pass
class PasswordResetForm(forms.Form): email = forms.EmailField( label=_("E-mail"), max_length=254, widget=forms.TextInput(attrs={'class': 'form-control'})) captcha = CustomCatpchaField( label=_('Type the letters you see in the box'), widget=CaptchaTextInput(attrs={'class': 'form-control'})) def clean_email(self): """ Validates that a user exists with the given e-mail address. """ email = self.cleaned_data["email"] self_reg = get_setting('module', 'users', 'selfregistration') self.email = email self.users_cache = User.objects.filter(email__iexact=email, is_active=True) if len(self.users_cache) == 0: if self_reg: raise forms.ValidationError( mark_safe( _('That e-mail address doesn\'t have an associated user account. Are you sure you\'ve <a href="/accounts/register" >registered</a>?' ))) else: raise forms.ValidationError( _("That e-mail address doesn't have an associated user account." )) return email def save( self, email_template_name='registration/password_reset_email_user_list.html', **kwargs): """ Generates a one-use only link for resetting password and sends to the designated email. The email will contain links for resetting passwords for all accounts associated to the email. """ email_template_name = 'registration/password_reset_email_user_list.html' domain_override = kwargs.get('domain_override', False) use_https = kwargs.get('use_https', False) token_generator = kwargs.get('token_generator', default_token_generator) user_list = [] for user in self.users_cache: user_list.append({ 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'user': user, 'token': token_generator.make_token(user), }) if not domain_override: site_name = get_setting('site', 'global', 'sitedisplayname') else: site_name = domain_override site_url = get_setting('site', 'global', 'siteurl') t = loader.get_template(email_template_name) c = { 'email': self.email, 'site_url': site_url, 'site_name': site_name, 'user_list': user_list, 'protocol': use_https and 'https' or 'http', } from_email = get_setting( 'site', 'global', 'siteemailnoreplyaddress') or settings.DEFAULT_FROM_EMAIL email = Email(sender=from_email, recipient=user.email, subject=_("Password reset on %s") % site_name, body=t.render(context=c)) email.send()