def __init__(self, *args, **kwargs): super(FileForm, self).__init__(*args, **kwargs) default_groups = Group.objects.filter(status=True, status_detail="active") if args: post_data = args[0] else: post_data = None if self.user and not self.user.profile.is_superuser: 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 if self.instance and self.instance.pk: self.fields['file_sub_cat'].queryset = FilesCategory.objects.filter( parent=self.instance.file_cat) if post_data: file_cat = post_data.get('file_cat', '0') if file_cat and file_cat != '0' and file_cat != u'': file_cat = FilesCategory.objects.get(pk=int(file_cat)) self.fields['file_sub_cat'].queryset = FilesCategory.objects.filter(parent=file_cat) if 'file' in self.fields: self.fields['file'].validators = [FileValidator()]
def __init__(self, *args, **kwargs): super(PhotoUploadForm, self).__init__(*args, **kwargs) self.fields['photo'].validators = [ FileValidator(allowed_extensions=( '.jpeg', '.jpg', '.png', )) ]
class ChapterAdminForm(TendenciBaseForm): mission = forms.CharField(required=False, widget=TinyMCE(attrs={'style':'width:100%'}, mce_attrs={'storme_app_label':Chapter._meta.app_label, 'storme_model':Chapter._meta.model_name.lower()})) content = forms.CharField(required=False, widget=TinyMCE(attrs={'style':'width:100%'}, mce_attrs={'storme_app_label':Chapter._meta.app_label, 'storme_model':Chapter._meta.model_name.lower()})) notes = forms.CharField(required=False, widget=TinyMCE(attrs={'style':'width:100%'}, mce_attrs={'storme_app_label':Chapter._meta.app_label, 'storme_model':Chapter._meta.model_name.lower()})) group = forms.ModelChoiceField(queryset=Group.objects.filter(status=True, status_detail="active").order_by('name')) status_detail = forms.ChoiceField( choices=(('active','Active'),('inactive','Inactive'), ('pending','Pending'),)) photo_upload = forms.FileField(label=_('Featured Image'), required=False, validators=[FileValidator(allowed_extensions=('.jpg', '.jpeg', '.gif', '.png'))],) class Meta: model = Chapter fields = ( 'title', 'slug', 'entity', 'group', 'mission', 'content', 'notes', 'photo_upload', 'contact_name', 'contact_email', 'join_link', 'tags', 'allow_anonymous_view', 'syndicate', 'status_detail', ) def __init__(self, *args, **kwargs): super(ChapterAdminForm, self).__init__(*args, **kwargs) if self.instance.pk: self.fields['mission'].widget.mce_attrs['app_instance_id'] = self.instance.pk self.fields['content'].widget.mce_attrs['app_instance_id'] = self.instance.pk self.fields['notes'].widget.mce_attrs['app_instance_id'] = self.instance.pk else: self.fields['mission'].widget.mce_attrs['app_instance_id'] = 0 self.fields['content'].widget.mce_attrs['app_instance_id'] = 0 self.fields['notes'].widget.mce_attrs['app_instance_id'] = 0 if self.instance.featured_image: self.fields['photo_upload'].help_text = 'Current image: <a target="_blank" href="/files/%s/">%s</a>' % (self.instance.featured_image.pk, basename(self.instance.featured_image.file.name)) self.fields['photo_upload'].required = False
def __init__(self, *args, **kwargs): self.chapter = kwargs.pop('chapter') super(ChapterMembershipUploadForm, self).__init__(*args, **kwargs) self.fields['upload_file'].validators = [ FileValidator(allowed_extensions=['.csv'], allowed_mimetypes=['text/csv', 'text/plain']) ] if self.chapter: self.fields['key'].choices = (( 'username,membership_type_id', _('username and membership_type_id')), )
def __init__(self, *args, **kwargs): if 'user' in kwargs: self.user = kwargs.pop('user', None) else: self.user = None request_data = kwargs.pop('request_data') super(TinymceUploadForm, self).__init__(*args, **kwargs) if request_data.method.lower() == 'post': upload_type = request_data.POST.get('upload_type', 'other') else: upload_type = request_data.GET.get('upload_type', 'other') allowed_exts = get_allowed_upload_file_exts(upload_type) self.fields['file'].validators = [ FileValidator(allowed_extensions=allowed_exts) ]
def __init__(self, *args, **kwargs): super(FileForm, self).__init__(*args, **kwargs) default_groups = Group.objects.filter(status=True, status_detail="active") if args: post_data = args[0] else: post_data = None if not self.user.profile.is_superuser: del self.fields['status_detail'] if get_setting('module', 'user_groups', 'permrequiredingd') == 'change': filters = get_groups_query_filters(self.user, ) else: filters = get_query_filters(self.user, 'user_groups.view_group', **{'perms_field': False}) default_groups = default_groups.filter(filters).distinct() self.fields['group'].queryset = default_groups self.fields['group'].empty_label = None if self.instance and self.instance.pk: self.fields[ 'file_sub_cat'].queryset = FilesCategory.objects.filter( parent=self.instance.file_cat) if post_data: file_cat = post_data.get('file_cat', '0') if file_cat and file_cat != '0' and file_cat != u'': file_cat = FilesCategory.objects.get(pk=int(file_cat)) self.fields[ 'file_sub_cat'].queryset = FilesCategory.objects.filter( parent=file_cat) if 'file' in self.fields: self.fields['file'].validators = [FileValidator()]
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()
class MultiFileForm(BetterForm): files = MultiFileField(min_num=1, validators=[FileValidator()]) group = forms.ChoiceField(required=True, choices=[]) tags = forms.CharField(required=False) file_cat = forms.ModelChoiceField(label=_("Category"), queryset=FilesCategory.objects.filter(parent=None), empty_label="-----------", required=False) file_sub_cat = forms.ModelChoiceField(label=_("Sub-Category"), queryset=FilesCategory.objects.none(), empty_label=_("Please choose a category first"), required=False) allow_anonymous_view = forms.BooleanField(label=_("Public can View"), initial=True, required=False) group_perms = GroupPermissionField() user_perms = UserPermissionField() member_perms = MemberPermissionField() class Meta: fieldsets = ( (_('File Information'), { 'fields': ('files', 'tags', 'group', ) }), (_('Category'), {'fields': ('file_cat', 'file_sub_cat')}), (_('Permissions'), {'fields': ('allow_anonymous_view',)}), (_('Advanced Permissions'), {'classes': ('collapse',), 'fields': ( 'user_perms', 'member_perms', 'group_perms', )}), ) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) if self.request: self.user = self.request.user else: self.user = None super(MultiFileForm, self).__init__(*args, **kwargs) default_groups = Group.objects.filter(status=True, status_detail="active") if args: post_data = args[0] else: post_data = None if self.user and not self.user.profile.is_superuser: 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 # set up the sub category choices if post_data: file_cat = post_data.get('file_cat', '0') if file_cat and file_cat != '0' and file_cat != u'': [file_cat] = FilesCategory.objects.filter(pk=int(file_cat))[:1] or [None] if file_cat: self.fields['file_sub_cat'].queryset = FilesCategory.objects.filter(parent=file_cat) def clean_user_perms(self): user_perm_bits = [] value = self.cleaned_data['user_perms'] if value: if 'allow_user_view' in value: user_perm_bits.append(True) else: user_perm_bits.append(False) if 'allow_user_edit' in value: user_perm_bits.append(True) else: user_perm_bits.append(False) value = tuple(user_perm_bits) else: value = (False, False,) return value def clean_member_perms(self): member_perm_bits = [] value = self.cleaned_data['member_perms'] if value: if 'allow_member_view' in value: member_perm_bits.append(True) else: member_perm_bits.append(False) if 'allow_member_edit' in value: member_perm_bits.append(True) else: member_perm_bits.append(False) value = tuple(member_perm_bits) else: value = (False, False,) return value def clean_group_perms(self): value = self.cleaned_data['group_perms'] groups_and_perms = [] if value: for item in value: perm, group_pk = item.split('_') groups_and_perms.append((group_pk, perm,)) value = tuple(groups_and_perms) return value 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 save(self, *args, **kwargs): data = self.cleaned_data counter = 0 files = data.get('files') tags = data.get('tags') group = data.get('group') file_cat = data.get('file_cat', None) file_sub_cat = data.get('file_sub_cat', None) is_public = data.get('allow_anonymous_view', False) for new_file in files: file = File( file=new_file, tags=tags, group=group, allow_anonymous_view=is_public, file_cat=file_cat, file_sub_cat=file_sub_cat) file.save() # update all permissions and save the model file = update_perms_and_save(self.request, self, file) #setup categories category = Category.objects.get_for_object(file, 'category') sub_category = Category.objects.get_for_object(file, 'sub_category') ## update the category of the file category_removed = False category = file.file_cat.name if file.file_cat else u'' if category: Category.objects.update(file, category, 'category') else: # remove category_removed = True Category.objects.remove(file, 'category') Category.objects.remove(file, 'sub_category') if not category_removed: # update the sub category of the file sub_category = file.file_sub_cat.name if file.file_sub_cat else u'' if sub_category: Category.objects.update(file, sub_category, 'sub_category') else: # remove Category.objects.remove(file, 'sub_category') #Save relationships file.save() counter += 1 return counter
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
class ChapterForm(TendenciBaseForm): mission = forms.CharField(required=False, widget=TinyMCE(attrs={'style':'width:100%'}, mce_attrs={'storme_app_label':Chapter._meta.app_label, 'storme_model':Chapter._meta.model_name.lower()})) content = forms.CharField(required=False, widget=TinyMCE(attrs={'style':'width:100%'}, mce_attrs={'storme_app_label':Chapter._meta.app_label, 'storme_model':Chapter._meta.model_name.lower()})) notes = forms.CharField(required=False, widget=TinyMCE(attrs={'style':'width:100%'}, mce_attrs={'storme_app_label':Chapter._meta.app_label, 'storme_model':Chapter._meta.model_name.lower()})) photo_upload = forms.FileField(label=_('Featured Image'), required=False, validators=[FileValidator(allowed_extensions=('.jpg', '.jpeg', '.gif', '.png'))],) class Meta: model = Chapter fields = ( 'title', 'slug', 'entity', 'group', 'mission', 'content', 'notes', 'sponsors', 'photo_upload', 'contact_name', 'contact_email', 'join_link', 'tags', 'allow_anonymous_view', 'syndicate', 'status_detail', ) fieldsets = [('Chapter Information', { 'fields': ['title', 'slug', 'entity', 'group', 'mission', 'content', 'notes', 'sponsors', 'photo_upload', 'contact_name', 'contact_email', 'join_link', 'tags' ], 'legend': '', }), ('Permissions', { 'fields': ['allow_anonymous_view', 'user_perms', 'member_perms', 'group_perms', ], 'classes': ['permissions'], }), ('Administrator Only', { 'fields': ['syndicate', 'status_detail'], 'classes': ['admin-only'], })] status_detail = forms.ChoiceField(choices=(('active','Active'),('pending','Pending'))) def __init__(self, *args, **kwargs): super(ChapterForm, self).__init__(*args, **kwargs) if self.instance.featured_image: self.fields['photo_upload'].help_text = 'Current image: <a target="_blank" href="/files/%s/">%s</a>' % (self.instance.featured_image.pk, basename(self.instance.featured_image.file.name)) if self.instance.pk: self.fields['mission'].widget.mce_attrs['app_instance_id'] = self.instance.pk self.fields['content'].widget.mce_attrs['app_instance_id'] = self.instance.pk self.fields['notes'].widget.mce_attrs['app_instance_id'] = self.instance.pk else: self.fields['mission'].widget.mce_attrs['app_instance_id'] = 0 self.fields['content'].widget.mce_attrs['app_instance_id'] = 0 self.fields['notes'].widget.mce_attrs['app_instance_id'] = 0 def save(self, *args, **kwargs): chapter = super(ChapterForm, self).save(*args, **kwargs) # save photo if 'photo_upload' in self.cleaned_data: photo = self.cleaned_data['photo_upload'] if photo: chapter.save(photo=photo) return chapter
def __init__(self, *args, **kwargs): if hasattr(self, 'user'): kwargs.update({'user': self.user}) super(JobForm, self).__init__(*args, **kwargs) if self.instance.header_image: print('A' * 30) print(self.instance.header_image) self.fields['header_image'].help_text = '<input name="remove_photo" id="id_remove_photo" type="checkbox"/> %s: <a target="_blank" href="/files/%s/">%s</a>' % (_('Remove current image'), self.instance.header_image.id, basename(self.instance.header_image.file.name)) else: self.fields.pop('remove_photo') self.fields['header_image'].validators = [FileValidator(allowed_extensions=get_allowed_upload_file_exts('image'))] 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 += [ '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 __init__(self, *args, **kwargs): super(FileForm, self).__init__(*args, **kwargs) self.fields['file'].validators = [ FileValidator(allowed_extensions=get_allowed_upload_file_exts( file_type='image')) ]