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'))
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
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
class RegistrationForm(forms.Form): """ Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but should either preserve the base ``save()`` or implement a ``save()`` which accepts the ``profile_callback`` keyword argument and passes it through to ``RegistrationProfile.objects.create_inactive_user()``. """ username = forms.CharField( label=_('Username'), max_length=150, widget=forms.TextInput(attrs=attrs_dict), help_text=_( '150 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[UnicodeUsernameValidator()], ) email = EmailVerificationField(label=_(u'Email Address'), attrs=attrs_dict) password1 = forms.CharField( widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), label=_(u'Password'), help_text=_( "Use at least 8 characters and 1 number or special character")) password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), label=_(u'Password (confirm)')) def clean_username(self): """ Validate that the username is alphanumeric and is not already in use. """ value = self.cleaned_data['username'] if User.objects.filter(username__iexact=value).count() > 0: raise forms.ValidationError( _(u'This username is already taken. Please choose another.')) return value def clean(self): """ Verifiy that the values entered into the two password fields match. Note that an error here will end up in ``non_field_errors()`` because it doesn't apply to a single field. """ 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, profile_callback=None): """ Create the new ``User`` and ``RegistrationProfile``, and returns the ``User``. This is essentially a light wrapper around ``RegistrationProfile.objects.create_inactive_user()``, feeding it the form data and a profile callback (see the documentation on ``create_inactive_user()`` for details) if supplied. """ new_user = RegistrationProfile.objects.create_inactive_user( username=self.cleaned_data['username'], password=self.cleaned_data['password1'], email=self.cleaned_data['email'], profile_callback=profile_callback) return new_user
class NewsForm(TendenciBaseForm): body = forms.CharField(required=False, widget=TinyMCE(attrs={'style': 'width:100%;'}, mce_attrs={ 'storme_app_label': News._meta.app_label, 'storme_model': News._meta.model_name.lower() })) release_dt = forms.SplitDateTimeField(label=_('Release Date/Time')) status_detail = forms.ChoiceField(choices=(('active', _('Active')), ('inactive', _('Inactive')), ('pending', _('Pending')))) email = EmailVerificationField(label=_("Email"), required=False) syndicate = forms.BooleanField(label=_('Include in RSS Feed'), required=False, initial=True) contributor_type = forms.ChoiceField(choices=CONTRIBUTOR_CHOICES, initial=News.CONTRIBUTOR_AUTHOR, widget=forms.RadioSelect()) photo_upload = forms.FileField( label=_('Thumbnail Image'), required=False, help_text= _('The thumbnail image can be used on your homepage or sidebar if it is setup in your theme. It will not display on the news page.' )) remove_photo = forms.BooleanField(label=_('Remove the current photo'), required=False) groups = forms.MultipleChoiceField( required=True, choices=[], help_text= _('Hold down "Control", or "Command" on a Mac, to select more than one.' )) class Meta: model = News fields = ( 'headline', 'slug', 'summary', 'body', 'groups', 'photo_upload', 'source', 'website', 'release_dt', 'timezone', 'contributor_type', 'first_name', 'last_name', 'google_profile', 'phone', 'fax', 'email', 'tags', 'allow_anonymous_view', 'syndicate', 'user_perms', 'member_perms', 'group_perms', 'status_detail', ) fieldsets = [(_('News Information'), { 'fields': [ 'headline', 'slug', 'summary', 'body', 'groups', 'tags', 'photo_upload', 'source', 'website', 'release_dt', 'timezone', ], 'legend': '' }), (_('Contributor'), { 'fields': ['contributor_type', 'google_profile'], 'classes': ['boxy-grey'], }), (_('Author'), { 'fields': [ 'first_name', 'last_name', 'phone', 'fax', 'email', ], 'classes': ['contact'], }), (_('Permissions'), { 'fields': [ 'allow_anonymous_view', 'user_perms', 'member_perms', 'group_perms', ], 'classes': ['permissions'], }), (_('Administrator Only'), { 'fields': ['syndicate', 'status_detail'], 'classes': ['admin-only'], })] def clean_photo_upload(self): photo_upload = self.cleaned_data['photo_upload'] if photo_upload: extension = splitext(photo_upload.name)[1] # check the extension if extension.lower() not in ALLOWED_LOGO_EXT: raise forms.ValidationError( _('The photo must be of jpg, gif, or png image type.')) # check the image header image_type = '.%s' % imghdr.what('', photo_upload.read()) if image_type not in ALLOWED_LOGO_EXT: raise forms.ValidationError( _('The photo is an invalid image. Try uploading another photo.' )) max_upload_size = get_max_file_upload_size() if photo_upload.size > max_upload_size: raise forms.ValidationError( _('Please keep filesize under %(max_upload_size)s. Current filesize %(upload_size)s' ) % { 'max_upload_size': filesizeformat(max_upload_size), 'upload_size': filesizeformat(photo_upload.size) }) return photo_upload def clean_groups(self): group_ids = self.cleaned_data['groups'] groups = [] for group_id in group_ids: try: group = Group.objects.get(pk=group_id) groups.append(group) except Group.DoesNotExist: raise forms.ValidationError(_('Invalid group selected.')) return groups 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): news = super(NewsForm, self).save(*args, **kwargs) if self.cleaned_data.get('remove_photo'): news.thumbnail = None return news def __init__(self, *args, **kwargs): super(NewsForm, self).__init__(*args, **kwargs) if self.instance.pk: self.fields['body'].widget.mce_attrs[ 'app_instance_id'] = self.instance.pk else: self.fields['body'].widget.mce_attrs['app_instance_id'] = 0 self.fields['groups'].initial = [ Group.objects.get_initial_group_id() ] default_groups = Group.objects.filter(status=True, status_detail="active") #if not self.user.profile.is_superuser: if not self.user.is_superuser: if 'status_detail' in self.fields: self.fields.pop('status_detail') filters = get_query_filters(self.user, 'user_groups.view_group', **{'perms_field': False}) groups = default_groups.filter(filters).distinct() groups_list = list(groups.values_list('pk', 'name')) users_groups = self.user.profile.get_groups() for g in users_groups: if [g.id, g.name] not in groups_list: groups_list.append([g.id, g.name]) else: groups_list = default_groups.values_list('pk', 'name') self.fields['groups'].choices = groups_list self.fields['google_profile'].help_text = mark_safe( GOOGLE_PLUS_HELP_TEXT) self.fields['timezone'].initial = settings.TIME_ZONE # only show the remove photo checkbox if there is already a thumbnail if self.instance.thumbnail: self.fields[ 'photo_upload'].help_text = '<input name="remove_photo" id="id_remove_photo" type="checkbox"/> Remove current image: <a target="_blank" href="/files/%s/">%s</a>' % ( self.instance.thumbnail.pk, basename(self.instance.thumbnail.file.name)) else: self.fields.pop('remove_photo') self.fields['release_dt'].initial = datetime.now()
class DirectoryForm(TendenciBaseForm): body = forms.CharField(label=_("Description"), required=False, widget=TinyMCE( attrs={'style': 'width:100%'}, mce_attrs={ 'storme_app_label': Directory._meta.app_label, 'storme_model': Directory._meta.model_name.lower() })) logo = forms.FileField( required=False, help_text=_('Company logo. Only jpg, gif, or png images.')) 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.CharField( error_messages={'required': _('Please select a payment method.')}) activation_dt = forms.SplitDateTimeField(initial=datetime.now()) expiration_dt = forms.SplitDateTimeField(initial=datetime.now()) email = EmailVerificationField(label=_("Email"), required=False) email2 = EmailVerificationField(label=_("Email 2"), required=False) country = CountrySelectField(label=_("Country"), required=False) pricing = forms.ModelChoiceField(queryset=DirectoryPricing.objects.filter( status=True).order_by('duration'), **request_duration_defaults) cat = forms.ModelChoiceField( label=_("Category"), queryset=DirectoryCategory.objects.filter(parent=None), empty_label="-----------", required=False) sub_cat = forms.ModelChoiceField( label=_("Subcategory"), queryset=DirectoryCategory.objects.none(), empty_label=_("Please choose a category first"), required=False) class Meta: model = Directory fields = ( 'headline', 'slug', 'summary', 'body', 'logo', 'source', 'timezone', 'first_name', 'last_name', 'address', 'address2', 'city', 'state', 'zip_code', 'country', 'phone', 'phone2', 'fax', 'email', 'email2', 'website', 'tags', 'pricing', 'list_type', 'payment_method', 'activation_dt', 'expiration_dt', 'allow_anonymous_view', 'allow_user_view', 'allow_user_edit', 'syndicate', 'user_perms', 'member_perms', 'group_perms', 'cat', 'sub_cat', 'status_detail', ) fieldsets = [(_('Directory Information'), { 'fields': [ 'headline', 'slug', 'summary', 'body', 'logo', 'tags', 'source', 'timezone', 'activation_dt', 'pricing', 'expiration_dt', ], 'legend': '' }), (_('Payment'), { 'fields': ['list_type', 'payment_method'], 'classes': ['payment_method'], }), (_('Contact'), { 'fields': [ 'first_name', 'last_name', 'address', 'address2', 'city', 'state', 'zip_code', 'country', 'phone', 'phone2', 'fax', 'email', 'email2', 'website' ], 'classes': ['contact'], }), (_('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): super(DirectoryForm, self).__init__(*args, **kwargs) if self.instance.pk: self.fields['body'].widget.mce_attrs[ 'app_instance_id'] = self.instance.pk if self.user.profile.is_superuser: self.fields['status_detail'].choices = ( ('active', _('Active')), ('inactive', _('Inactive')), ('pending', _('Pending')), ('paid - pending approval', _('Paid - Pending Approval')), ) else: self.fields['body'].widget.mce_attrs['app_instance_id'] = 0 if self.instance.logo: self.initial['logo'] = self.instance.logo if not self.user.profile.is_superuser: if 'status_detail' in self.fields: self.fields.pop('status_detail') if 'payment_method' in self.fields: self.fields['payment_method'] = forms.ChoiceField( widget=forms.RadioSelect, choices=get_payment_method_choices(self.user)) if 'pricing' in self.fields: self.fields['pricing'].choices = get_duration_choices(self.user) self.fields['timezone'].initial = settings.TIME_ZONE # 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:directories_category_changelist'), _('Manage Categories'), )) if self.instance and self.instance.pk: self.fields['sub_cat'].queryset = DirectoryCategory.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 = DirectoryCategory.objects.get(pk=int(cat)) self.fields[ 'sub_cat'].queryset = DirectoryCategory.objects.filter( parent=cat) # expiration_dt = activation_dt + requested_duration fields_to_pop = ['expiration_dt'] if not self.user.profile.is_superuser: fields_to_pop += [ 'slug', 'entity', 'allow_anonymous_view', 'user_perms', 'member_perms', 'group_perms', 'post_dt', 'activation_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 clean_logo(self): logo = self.cleaned_data['logo'] if logo: try: extension = splitext(logo.name)[1] # check the extension if extension.lower() not in ALLOWED_LOGO_EXT: raise forms.ValidationError( _('The logo must be of jpg, gif, or png image type.')) # check the image header image_type = '.%s' % imghdr.what('', logo.read()) if image_type not in ALLOWED_LOGO_EXT: raise forms.ValidationError( _('The logo is an invalid image. Try uploading another logo.' )) max_upload_size = get_max_file_upload_size() if logo.size > max_upload_size: raise forms.ValidationError( _('Please keep filesize under %(max_upload_size)s. Current filesize %(logo_size)s' ) % { 'max_upload_size': filesizeformat(max_upload_size), 'logo_size': filesizeformat(logo.size) }) except IOError: logo = None return logo def clean_headline(self): """ remove extra leading and trailing white spaces """ return self.cleaned_data.get('headline', '').strip() def save(self, *args, **kwargs): from tendenci.apps.files.models import File directory = super(DirectoryForm, self).save(*args, **kwargs) content_type = ContentType.objects.get( app_label=Directory._meta.app_label, model=Directory._meta.model_name) if 'pricing' in self.cleaned_data: directory.requested_duration = self.cleaned_data[ 'pricing'].duration if self.cleaned_data['logo']: file_object, created = File.objects.get_or_create( file=self.cleaned_data['logo'], defaults={ 'name': self.cleaned_data['logo'].name, 'content_type': content_type, 'object_id': directory.pk, 'is_public': directory.allow_anonymous_view, 'tags': directory.tags, 'creator': self.user, 'owner': self.user, }) directory.logo_file = file_object directory.save(log=False) # clear logo; if box checked if self.cleaned_data['logo'] is False: directory.logo_file = None directory.save(log=False) File.objects.filter(content_type=content_type, object_id=directory.pk).delete() return directory
class ProfileForm(TendenciBaseForm): first_name = forms.CharField( label=_("First Name"), max_length=100, error_messages={'required': _('First Name is a required field.')}) last_name = forms.CharField( label=_("Last Name"), max_length=100, error_messages={'required': _('Last Name is a required field.')}) email = EmailVerificationField( label=_("Email"), error_messages={'required': _('Email is a required field.')}) email2 = EmailVerificationField(label=_("Secondary Email"), required=False) initials = forms.CharField(label=_("Initial"), max_length=100, required=False, widget=forms.TextInput(attrs={'size': '10'})) display_name = forms.CharField( label=_("Display name"), max_length=100, required=False, widget=forms.TextInput(attrs={'size': '30'})) url = forms.CharField(label=_("Web Site"), max_length=100, required=False, widget=forms.TextInput(attrs={'size': '40'})) company = forms.CharField( label=_("Company"), max_length=100, required=False, error_messages={'required': _('Company is a required field.')}, widget=forms.TextInput(attrs={'size': '45'})) department = forms.CharField(label=_("Department"), max_length=100, required=False, widget=forms.TextInput(attrs={'size': '35'})) address = forms.CharField( label=_("Address"), max_length=150, required=False, error_messages={'required': _('Address is a required field.')}, widget=forms.TextInput(attrs={'size': '45'})) address2 = forms.CharField(label=_("Address2"), max_length=100, required=False, widget=forms.TextInput(attrs={'size': '40'})) city = forms.CharField( label=_("City"), max_length=50, required=False, error_messages={'required': _('City is a required field.')}, widget=forms.TextInput(attrs={'size': '15'})) state = forms.CharField( label=_("State"), max_length=50, required=False, error_messages={'required': _('State is a required field.')}, widget=forms.TextInput(attrs={'size': '5'})) zipcode = forms.CharField( label=_("Zipcode"), max_length=50, required=False, error_messages={'required': _('Zipcode is a required field.')}, widget=forms.TextInput(attrs={'size': '10'})) country = CountrySelectField(label=_("Country"), required=False) address_2 = forms.CharField(label=_("Address"), max_length=64, required=False, widget=forms.TextInput(attrs={'size': '45'})) address2_2 = forms.CharField(label=_("Address2"), max_length=64, required=False, widget=forms.TextInput(attrs={'size': '40'})) city_2 = forms.CharField(label=_("City"), max_length=35, required=False, widget=forms.TextInput(attrs={'size': '15'})) state_2 = forms.CharField(label=_("State"), max_length=35, required=False, widget=forms.TextInput(attrs={'size': '5'})) zipcode_2 = forms.CharField(label=_("Zipcode"), max_length=16, required=False, widget=forms.TextInput(attrs={'size': '10'})) country_2 = CountrySelectField(label=_("Country"), required=False) mailing_name = forms.CharField( label=_("Mailing Name"), max_length=120, required=False, error_messages={'required': _('Mailing name is a required field.')}, widget=forms.TextInput(attrs={'size': '30'})) username = forms.RegexField( regex=r'^[\w.@+-]+$', max_length=30, widget=forms.TextInput(attrs=attrs_dict), label=_(u'Username'), help_text= _("Required. Allowed characters are letters, digits, at sign (@), period (.), plus sign (+), dash (-), and underscore (_)." ), error_messages={ 'invalid': _('Allowed characters are letters, digits, at sign (@), period (.), plus sign (+), dash (-), and underscore (_).' ) }) password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput(attrs=attrs_dict)) password2 = forms.CharField( label=_("Password (again)"), widget=forms.PasswordInput(attrs=attrs_dict), help_text=_("Enter the same password as above, for verification.")) security_level = forms.ChoiceField(initial="user", choices=( ('user', _('User')), ('staff', _('Staff')), ('superuser', _('Superuser')), )) interactive = forms.ChoiceField(initial=1, choices=( (1, 'Interactive'), (0, _('Not Interactive (no login)')), )) direct_mail = forms.ChoiceField(initial=True, choices=( (True, _('Yes')), (False, _('No')), )) notes = forms.CharField(label=_("Notes"), max_length=1000, required=False, widget=forms.Textarea(attrs={'rows': '3'})) admin_notes = forms.CharField(label=_("Admin Notes"), max_length=1000, required=False, widget=forms.Textarea(attrs={'rows': '3'})) language = forms.ChoiceField(initial="en", choices=get_languages_with_local_name()) dob = forms.DateField(required=False, widget=SelectDateWidget(None, list(range(1920, THIS_YEAR)))) status_detail = forms.ChoiceField(choices=( ('active', _('Active')), ('inactive', _('Inactive')), ('pending', _('Pending')), )) class Meta: model = Profile fields = ( 'salutation', 'first_name', 'last_name', 'username', 'password1', 'password2', 'phone', 'phone2', 'fax', 'work_phone', 'home_phone', 'mobile_phone', 'email', 'email2', 'company', 'position_title', 'position_assignment', 'display_name', 'hide_in_search', 'hide_phone', 'hide_email', 'hide_address', 'initials', 'sex', 'mailing_name', 'address', 'address2', 'city', 'state', 'zipcode', 'county', 'country', 'address_2', 'address2_2', 'city_2', 'state_2', 'zipcode_2', 'county_2', 'country_2', 'url', 'dob', 'ssn', 'spouse', 'time_zone', 'language', 'department', 'education', 'student', 'direct_mail', 'notes', 'interactive', 'allow_anonymous_view', 'admin_notes', 'security_level', 'status_detail', ) def __init__(self, *args, **kwargs): if 'user_this' in kwargs: self.user_this = kwargs.pop('user_this', None) else: self.user_this = None if 'user_current' in kwargs: self.user_current = kwargs.pop('user_current', None) else: self.user_current = None if 'required_fields_list' in kwargs: self.required_fields_list = kwargs.pop('required_fields_list', None) else: self.required_fields_list = None super(ProfileForm, self).__init__(*args, **kwargs) if self.user_this: self.fields['first_name'].initial = self.user_this.first_name self.fields['last_name'].initial = self.user_this.last_name self.fields['username'].initial = self.user_this.username self.fields['email'].initial = self.user_this.email if self.user_this.is_superuser: self.fields['security_level'].initial = "superuser" elif self.user_this.is_staff: self.fields['security_level'].initial = "staff" else: self.fields['security_level'].initial = "user" if self.user_this.is_active == 1: self.fields['interactive'].initial = 1 else: self.fields['interactive'].initial = 0 del self.fields['password1'] del self.fields['password2'] if not self.user_current.profile.is_superuser: del self.fields['admin_notes'] del self.fields['security_level'] del self.fields['status_detail'] if self.user_current.profile.is_superuser and self.user_current == self.user_this: self.fields['security_level'].choices = (('superuser', _('Superuser')), ) if not self.user_current.profile.is_superuser: if 'status_detail' in self.fields: self.fields.pop('status_detail') # we make first_name, last_name, email, username and password as required field regardless # the rest of fields will be decided by the setting - UsersRequiredFields if self.required_fields_list: for field in self.required_fields_list: for myfield in self.fields: if field == self.fields[myfield].label: self.fields[myfield].required = True continue def clean_username(self): """ Validate that the username is alphanumeric and is not already in use. """ try: user = User.objects.get(username=self.cleaned_data['username']) if self.user_this and user.id == self.user_this.id and user.username == self.user_this.username: return 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): """ Verifiy that the values entered into the two password fields match. Note that an error here will end up in ``non_field_errors()`` because it doesn't apply to a single field. """ if not self.user_this: 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, request, user_edit, *args, **kwargs): """ Create a new user then create the user profile """ username = self.cleaned_data['username'] email = self.cleaned_data['email'] params = { 'first_name': self.cleaned_data['first_name'], 'last_name': self.cleaned_data['last_name'], 'email': self.cleaned_data['email'], } if not self.user_this: password = self.cleaned_data['password1'] new_user = User.objects.create_user(username, email, password) self.instance.user = new_user update_user(new_user, **params) else: # for update_subscription self.instance.old_email = user_edit.email params.update({'username': username}) update_user(user_edit, **params) if not self.instance.id: self.instance.creator = request.user self.instance.creator_username = request.user.username self.instance.owner = request.user self.instance.owner_username = request.user.username return super(ProfileForm, self).save(*args, **kwargs)
class ProfileAdminForm(TendenciBaseForm): first_name = forms.CharField( label=_("First Name"), max_length=100, error_messages={'required': _('First Name is a required field.')}) last_name = forms.CharField( label=_("Last Name"), max_length=100, error_messages={'required': _('Last Name is a required field.')}) email = EmailVerificationField( label=_("Email"), error_messages={'required': _('Email is a required field.')}) email2 = EmailVerificationField(label=_("Secondary Email"), required=False) username = forms.RegexField( regex=r'^[\w.@+-]+$', max_length=30, widget=forms.TextInput(attrs=attrs_dict), label=_(u'Username'), help_text= _("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only." )) password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput(attrs=attrs_dict)) password2 = forms.CharField( label=_("Password (again)"), widget=forms.PasswordInput(attrs=attrs_dict), help_text=_("Enter the same password as above, for verification.")) security_level = forms.ChoiceField(initial="user", choices=( ('user', _('User')), ('staff', _('Staff')), ('superuser', _('Superuser')), )) interactive = forms.ChoiceField(initial=1, choices=( (1, 'Interactive'), (0, _('Not Interactive (no login)')), )) language = forms.ChoiceField(initial="en", choices=get_languages_with_local_name()) status_detail = forms.ChoiceField(choices=( ('active', _('Active')), ('inactive', _('Inactive')), ('pending', _('Pending')), )) class Meta: model = Profile fields = ( 'salutation', 'first_name', 'last_name', 'username', 'password1', 'password2', 'phone', 'phone2', 'fax', 'work_phone', 'home_phone', 'mobile_phone', 'email', 'email2', 'company', 'position_title', 'position_assignment', 'display_name', 'hide_in_search', 'hide_phone', 'hide_email', 'hide_address', 'initials', 'sex', 'mailing_name', 'address', 'address2', 'city', 'state', 'zipcode', 'county', 'country', 'address_2', 'address2_2', 'city_2', 'state_2', 'zipcode_2', 'county_2', 'country_2', 'url', 'dob', 'ssn', 'spouse', 'time_zone', 'language', 'department', 'education', 'student', 'direct_mail', 'notes', 'interactive', 'allow_anonymous_view', 'admin_notes', 'security_level', 'status_detail', ) def __init__(self, *args, **kwargs): super(ProfileAdminForm, self).__init__(*args, **kwargs) if self.instance.id: self.fields['first_name'].initial = self.instance.user.first_name self.fields['last_name'].initial = self.instance.user.last_name self.fields['username'].initial = self.instance.user.username self.fields['email'].initial = self.instance.user.email self.fields['password1'].required = False self.fields['password2'].required = False self.fields['password1'].widget.attrs['readonly'] = True self.fields['password2'].widget.attrs['readonly'] = True if self.instance.user.is_superuser: self.fields['security_level'].initial = "superuser" elif self.instance.user.is_staff: self.fields['security_level'].initial = "staff" else: self.fields['security_level'].initial = "user" if self.instance.user.is_active == 1: self.fields['interactive'].initial = 1 else: self.fields['interactive'].initial = 0 def clean_username(self): """ Validate that the username is alphanumeric and is not already in use. """ try: user = User.objects.get( username__iexact=self.cleaned_data['username']) if self.instance.id and user.id == self.instance.user.id: return 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): """ Verifiy that the values entered into the two password fields match. Note that an error here will end up in ``non_field_errors()`` because it doesn't apply to a single field. """ if not self.instance.id: 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, *args, **kwargs): """ Create a new user then create the user profile """ request = kwargs.pop('request', None) username = self.cleaned_data['username'] email = self.cleaned_data['email'] params = { 'first_name': self.cleaned_data['first_name'], 'last_name': self.cleaned_data['last_name'], 'email': self.cleaned_data['email'], } if not self.instance.id: password = self.cleaned_data['password1'] new_user = User.objects.create_user(username, email, password) self.instance.user = new_user update_user(new_user, **params) else: self.instance.old_email = self.instance.user.email params.update({'username': username}) update_user(self.instance.user, **params) if not (request.user == self.instance.user and request.user.is_superuser): security_level = self.cleaned_data['security_level'] if security_level == 'superuser': self.instance.user.is_superuser = 1 self.instance.user.is_staff = 1 elif security_level == 'staff': self.instance.user.is_superuser = 0 self.instance.user.is_staff = 1 else: self.instance.user.is_superuser = 0 self.instance.user.is_staff = 0 interactive = self.cleaned_data['interactive'] try: interactive = int(interactive) except: interactive = 0 self.instance.user.is_active = interactive if not self.instance.id: self.instance.creator = request.user self.instance.creator_username = request.user.username self.instance.owner = request.user self.instance.owner_username = request.user.username self.instance.user.save() self.instance.save() return super(ProfileAdminForm, self).save(*args, **kwargs)
class RegistrationForm(forms.Form): """ Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but should either preserve the base ``save()`` or implement a ``save()`` which accepts the ``profile_callback`` keyword argument and passes it through to ``RegistrationProfile.objects.create_inactive_user()``. """ username = forms.RegexField(regex=r'^\w+$', max_length=30, widget=forms.TextInput(attrs=attrs_dict), label=_(u'username')) email = EmailVerificationField(label=_(u'email address'), attrs=attrs_dict) password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), label=_(u'password')) password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), label=_(u'password (again)')) def clean_username(self): """ Validate that the username is alphanumeric and is not already in use. """ try: user = User.objects.get( username__iexact=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): """ Verifiy that the values entered into the two password fields match. Note that an error here will end up in ``non_field_errors()`` because it doesn't apply to a single field. """ 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, profile_callback=None): """ Create the new ``User`` and ``RegistrationProfile``, and returns the ``User``. This is essentially a light wrapper around ``RegistrationProfile.objects.create_inactive_user()``, feeding it the form data and a profile callback (see the documentation on ``create_inactive_user()`` for details) if supplied. """ new_user = RegistrationProfile.objects.create_inactive_user( username=self.cleaned_data['username'], password=self.cleaned_data['password1'], email=self.cleaned_data['email'], profile_callback=profile_callback) return new_user
class LocationForm(TendenciBaseForm): photo_upload = forms.FileField(label=_('Logo'), required=False) remove_photo = forms.BooleanField(label=_('Remove the current logo'), required=False) status_detail = forms.ChoiceField( choices=(('active',_('Active')),('inactive',_('Inactive')), ('pending',_('Pending')),)) email = EmailVerificationField(label=_("Email"), required=False) country = CountrySelectField(label=_("Country"), required=False) class Meta: model = Location fields = ( 'location_name', 'slug', 'description', 'contact', 'address', 'address2', 'city', 'state', 'zipcode', 'country', 'phone', 'fax', 'email', 'website', 'latitude', 'longitude', 'photo_upload', 'hq', 'allow_anonymous_view', 'user_perms', 'member_perms', 'group_perms', 'status_detail', ) fieldsets = [(_('Location Information'), { 'fields': ['location_name', 'slug', 'description', 'latitude', 'longitude', 'photo_upload', 'hq', ], 'legend': '' }), (_('Contact'), { 'fields': ['contact', 'address', 'address2', 'city', 'state', 'zipcode', 'country', 'phone', 'fax', 'email', 'website' ], 'classes': ['contact'], }), (_('Permissions'), { 'fields': ['allow_anonymous_view', 'user_perms', 'member_perms', 'group_perms', ], 'classes': ['permissions'], }), (_('Administrator Only'), { 'fields': ['status_detail'], 'classes': ['admin-only'], })] def __init__(self, *args, **kwargs): super(LocationForm, self).__init__(*args, **kwargs) if self.user: if not self.user.profile.is_superuser: if 'status_detail' in self.fields: self.fields.pop('status_detail') if self.instance.logo: self.fields['photo_upload'].help_text = '<input name="remove_photo" id="id_remove_photo" type="checkbox"/> Remove current image: <a target="_blank" href="/files/%s/">%s</a>' % (self.instance.logo.pk, basename(self.instance.logo.file.name)) else: self.fields.pop('remove_photo') def clean_photo_upload(self): photo_upload = self.cleaned_data['photo_upload'] if photo_upload: extension = splitext(photo_upload.name)[1] # check the extension if extension.lower() not in ALLOWED_LOGO_EXT: raise forms.ValidationError(_('The logo must be of jpg, gif, or png image type.')) # check the image header image_type = '.%s' % imghdr.what('', photo_upload.read()) if image_type not in ALLOWED_LOGO_EXT: raise forms.ValidationError(_('The logo is an invalid image. Try uploading another logo.')) max_upload_size = get_max_file_upload_size() if photo_upload.size > max_upload_size: raise forms.ValidationError(_('Please keep filesize under %(max_upload_size)s. Current filesize %(upload_size)s') % { 'max_upload_size': filesizeformat(max_upload_size), 'upload_size': filesizeformat(photo_upload.size)}) return photo_upload def save(self, *args, **kwargs): location = super(LocationForm, self).save(*args, **kwargs) if self.cleaned_data.get('remove_photo'): location.logo = None return location
class ArticleForm(TendenciBaseForm): body = forms.CharField(required=False, widget=TinyMCE(attrs={'style': 'width:100%'}, mce_attrs={ 'storme_app_label': Article._meta.app_label, 'storme_model': Article._meta.model_name.lower() })) release_dt = SplitDateTimeField(label=_('Release Date/Time'), initial=datetime.now()) contributor_type = forms.ChoiceField(choices=CONTRIBUTOR_CHOICES, initial=Article.CONTRIBUTOR_AUTHOR, widget=forms.RadioSelect()) syndicate = forms.BooleanField(label=_('Include in RSS feed'), required=False, initial=True) status_detail = forms.ChoiceField(choices=( ('active', _('Active')), ('inactive', _('Inactive')), ('pending', _('Pending')), )) email = EmailVerificationField(label=_("Email"), required=False) group = forms.ChoiceField(required=True, choices=[]) class Meta: model = Article fields = ( 'headline', 'slug', 'summary', 'body', 'source', 'website', 'release_dt', 'timezone', 'contributor_type', 'first_name', 'last_name', 'google_profile', 'phone', 'fax', 'email', 'group', 'tags', 'allow_anonymous_view', 'syndicate', 'user_perms', 'member_perms', 'group_perms', 'status_detail', ) fieldsets = [(_('Article Information'), { 'fields': [ 'headline', 'slug', 'summary', 'body', 'group', 'tags', 'source', 'website', 'release_dt', 'timezone', ], 'legend': '' }), (_('Contributor'), { 'fields': ['contributor_type', 'google_profile'], 'classes': ['boxy-grey'], }), (_('Author'), { 'fields': [ 'first_name', 'last_name', 'phone', 'fax', 'email', ], 'classes': ['contact'], }), (_('Permissions'), { 'fields': [ 'allow_anonymous_view', 'user_perms', 'member_perms', 'group_perms', ], 'classes': ['permissions'], }), (_('Administrator Only'), { 'fields': ['syndicate', 'status_detail'], 'classes': ['admin-only'], })] def __init__(self, *args, **kwargs): super(ArticleForm, self).__init__(*args, **kwargs) if self.instance.pk: self.fields['body'].widget.mce_attrs[ 'app_instance_id'] = self.instance.pk else: self.fields['body'].widget.mce_attrs['app_instance_id'] = 0 self.fields['group'].initial = Group.objects.get_initial_group_id() default_groups = Group.objects.filter(status=True, status_detail="active") if self.user and not self.user.profile.is_superuser: if 'status_detail' in self.fields: self.fields.pop('status_detail') filters = get_query_filters(self.user, 'user_groups.view_group', **{'perms_field': False}) groups = default_groups.filter(filters).distinct() groups_list = list(groups.values_list('pk', 'name')) users_groups = self.user.profile.get_groups() for g in users_groups: if [g.id, g.name] not in groups_list: groups_list.append([g.id, g.name]) else: groups_list = default_groups.values_list('pk', 'name') self.fields['group'].choices = groups_list self.fields['google_profile'].help_text = mark_safe( GOOGLE_PLUS_HELP_TEXT) self.fields['timezone'].initial = settings.TIME_ZONE def clean_group(self): group_id = self.cleaned_data['group'] try: group = Group.objects.get(pk=group_id) return group except Group.DoesNotExist: raise forms.ValidationError(_('Invalid group selected.')) 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
class MakePaymentForm(forms.ModelForm): captcha = CaptchaField(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 ReliefAssessmentForm(BetterModelForm): first_name = forms.CharField(label=_("First Name"), max_length=100, error_messages={'required': 'First Name is a required field.'}) last_name = forms.CharField(label=_("Last Name"), max_length=100, error_messages={'required': 'Last Name is a required field.'}) # initials = forms.CharField(label=_("Initial"), max_length=100, required=False) phone = forms.CharField(label=_("Contact Phone"), max_length=50) phone2 = forms.CharField(label=_("Alternate Phone"), max_length=50, required=False) email = EmailVerificationField(label=_("Email"), error_messages={'required': 'Email is a required field.'}) email2 = EmailVerificationField(label=_("Alternate Email"), required=False) dob = forms.DateField(label=_("Date of Birth"), required=False, widget=SelectDateWidget(None, range(THIS_YEAR-100, THIS_YEAR))) company = forms.CharField(label=_("Company"), max_length=100, required=False) position_title = forms.CharField(label=_("Position Title"), max_length=50, required=False) education = forms.CharField(label=_("Education Level"), max_length=100, required=False) ethnicity = forms.ChoiceField(label="", required=False, choices=ETHNICITY_CHOICES, widget=forms.widgets.RadioSelect) case_notes = forms.CharField(required=False, widget=TinyMCE(attrs={'style':'width:100%'}, mce_attrs={'storme_app_label':ReliefAssessment._meta.app_label, 'storme_model':ReliefAssessment._meta.model_name.lower()})) items_provided = forms.CharField(required=False, widget=TinyMCE(attrs={'style':'width:100%'}, mce_attrs={'storme_app_label':ReliefAssessment._meta.app_label, 'storme_model':ReliefAssessment._meta.model_name.lower()})) class Meta: model = ReliefAssessment exclude = ('user',) fieldsets = [ ('Personal Information', { 'fields': ['first_name', 'last_name', 'initials', 'phone', 'phone2', 'email', 'email2', 'dob', 'id_number', 'issuing_authority', 'company', 'position_title', 'education', 'health_insurance', 'insurance_provider', ],}), ('Disaster Area Address', { 'fields': ['address', 'address2', 'city', 'state', 'zipcode', 'country', ],}), ('Alternate Address', { 'fields': ['alt_address', 'alt_address2', 'alt_city', 'alt_state', 'alt_zipcode', 'alt_country', ],}), ('Ethnicity', { 'fields': ['ethnicity', 'other_ethnicity', ],}), ('How many in your household are', { 'fields': ['below_2', 'between_3_11', 'between_12_18', 'between_19_59', 'above_60', ],}), ('Please identify services needed', { 'fields': ['ssa', 'dhs', 'children_needs', 'toiletries', 'employment', 'training', 'food', 'gas', 'prescription', 'other_service', ],}), ('For Internal Use', { 'fields': ['case_notes', 'items_provided', ],}), ] def __init__(self, *args, **kwargs): if 'edit' in kwargs: edit = kwargs.pop('edit', True) else: edit = True super(ReliefAssessmentForm, self).__init__(*args, **kwargs) if not edit: for name, field in self.fields.iteritems(): field.widget.attrs['disabled'] = True if self.instance.pk: self.fields['case_notes'].widget.mce_attrs['app_instance_id'] = self.instance.pk self.fields['items_provided'].widget.mce_attrs['app_instance_id'] = self.instance.pk self.fields['email'].initial = self.instance.user.email self.fields['first_name'].initial = self.instance.user.first_name self.fields['last_name'].initial = self.instance.user.last_name self.fields['initials'].initial = self.instance.user.profile.initials self.fields['phone'].initial = self.instance.user.profile.phone self.fields['phone2'].initial = self.instance.user.profile.phone2 self.fields['email2'].initial = self.instance.user.profile.email2 self.fields['dob'].initial = self.instance.user.profile.dob self.fields['company'].initial = self.instance.user.profile.company self.fields['position_title'].initial = self.instance.user.profile.position_title self.fields['education'].initial = self.instance.user.profile.education else: self.fields['case_notes'].widget.mce_attrs['app_instance_id'] = 0 self.fields['items_provided'].widget.mce_attrs['app_instance_id'] = 0 def clean(self): cleaned_data = self.cleaned_data if 'ethnicity' in cleaned_data: ethnicity = cleaned_data.get("ethnicity") other_text = cleaned_data.get("other_ethnicity") if ethnicity == 'other' and not other_text: raise forms.ValidationError("Please specify your ethnicity on the text box provided.") return cleaned_data def save(self, *args, **kwargs): relief = super(ReliefAssessmentForm, self).save(commit=False) user, created = Profile.get_or_create_user(**{ 'email': self.cleaned_data.get('email'), 'first_name': self.cleaned_data.get('first_name'), 'last_name': self.cleaned_data.get('last_name'), }) if created: profile = user.profile profile.initials = self.cleaned_data.get('initials') profile.phone = self.cleaned_data.get('phone') profile.phone2 = self.cleaned_data.get('phone2') profile.email2 = self.cleaned_data.get('email2') profile.dob = self.cleaned_data.get('dob') profile.company = self.cleaned_data.get('company') profile.position_title = self.cleaned_data.get('position_title') profile.education = self.cleaned_data.get('education') profile.save() relief.user = user relief.save()
class ArticleForm(TendenciBaseForm): body = forms.CharField(required=False, widget=TinyMCE(attrs={'style': 'width:100%'}, mce_attrs={ 'storme_app_label': Article._meta.app_label, 'storme_model': Article._meta.model_name.lower() })) release_dt = forms.SplitDateTimeField( label=_('Release Date/Time'), input_date_formats=['%Y-%m-%d', '%m/%d/%Y'], input_time_formats=['%I:%M %p', '%H:%M:%S']) contributor_type = forms.ChoiceField(choices=CONTRIBUTOR_CHOICES, initial=Article.CONTRIBUTOR_AUTHOR, widget=forms.RadioSelect()) thumbnail_file = forms.FileField( label=_('Thumbnail'), validators=[ FileValidator(allowed_extensions=('.jpg', '.jpeg', '.gif', '.png')) ], required=False, help_text=_('Only jpg, gif, or png images.')) syndicate = forms.BooleanField(label=_('Include in RSS feed'), required=False, initial=True) status_detail = forms.ChoiceField(choices=( ('active', _('Active')), ('inactive', _('Inactive')), ('pending', _('Pending')), )) email = EmailVerificationField(label=_("Email"), required=False) group = forms.ChoiceField(required=True, choices=[]) class Meta: model = Article fields = ( 'headline', 'slug', 'summary', 'body', 'thumbnail_file', 'source', 'website', 'release_dt', 'timezone', 'contributor_type', 'first_name', 'last_name', 'phone', 'fax', 'email', 'group', 'tags', 'allow_anonymous_view', 'syndicate', 'user_perms', 'member_perms', 'group_perms', 'status_detail', ) fieldsets = [(_('Article Information'), { 'fields': [ 'headline', 'slug', 'summary', 'body', 'thumbnail_file', 'group', 'tags', 'source', 'website', 'release_dt', 'timezone', ], 'legend': '' }), (_('Contributor'), { 'fields': [ 'contributor_type', ], 'classes': ['boxy-grey'], }), (_('Author'), { 'fields': [ 'first_name', 'last_name', 'phone', 'fax', 'email', ], 'classes': ['contact'], }), (_('Permissions'), { 'fields': [ 'allow_anonymous_view', 'user_perms', 'member_perms', 'group_perms', ], 'classes': ['permissions'], }), (_('Administrator Only'), { 'fields': ['syndicate', 'status_detail'], 'classes': ['admin-only'], })] def __init__(self, *args, **kwargs): super(ArticleForm, self).__init__(*args, **kwargs) if self.instance.pk: self.fields['body'].widget.mce_attrs[ 'app_instance_id'] = self.instance.pk else: self.fields['body'].widget.mce_attrs['app_instance_id'] = 0 self.fields['group'].initial = Group.objects.get_initial_group_id() default_groups = Group.objects.filter(status=True, status_detail="active") if self.instance.thumbnail: self.initial['thumbnail_file'] = self.instance.thumbnail.file if self.user and not self.user.profile.is_superuser: if 'status_detail' in self.fields: self.fields.pop('status_detail') filters = get_query_filters(self.user, 'user_groups.view_group', **{'perms_field': False}) groups = default_groups.filter(filters).distinct() groups_list = list(groups.values_list('pk', 'name')) users_groups = self.user.profile.get_groups() for g in users_groups: if [g.id, g.name] not in groups_list: groups_list.append([g.id, g.name]) else: groups_list = default_groups.values_list('pk', 'name') self.fields['group'].choices = groups_list self.fields['timezone'].initial = settings.TIME_ZONE self.fields['release_dt'].initial = datetime.now() def save(self, *args, **kwargs): article = super(ArticleForm, self).save(*args, **kwargs) content_type = ContentType.objects.get_for_model(Article) thumbnail_file = self.cleaned_data['thumbnail_file'] if thumbnail_file: file_object, created = File.objects.get_or_create( file=thumbnail_file, defaults={ 'name': thumbnail_file.name, 'content_type': content_type, 'object_id': article.pk, 'is_public': article.allow_anonymous_view, 'tags': article.tags, 'creator': self.user, 'owner': self.user, }) article.thumbnail = file_object article.save(log=False) else: # clear thumbnail if box checked if article.thumbnail: article.thumbnail = None article.save(log=False) File.objects.filter(content_type=content_type, object_id=article.pk).delete() return article def clean_group(self): group_id = self.cleaned_data['group'] try: group = Group.objects.get(pk=group_id) return group except Group.DoesNotExist: raise forms.ValidationError(_('Invalid group selected.')) 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