class FilePathFieldForm(forms.Form): description = "FilePathField options" field1 = forms.FilePathField(help_text='default', path=os.path.dirname(__file__)) field2 = forms.FilePathField(help_text='initial value', path=os.path.dirname(__file__), initial=__file__, match='^.*\.py$') field3 = forms.FilePathField(help_text='recursive directories', path=os.path.dirname(forms.__file__), recursive=True, allow_folders=True, allow_files=False, match='templates') field4 = forms.FilePathField(help_text='prefix', path=os.path.dirname(__file__), required=False) field5 = forms.FilePathField(help_text='disabled', path=os.path.dirname(__file__), disabled=True, required=False) template = Template(""" {% form %} {% part form.field4 prefix %}<i class="material-icons prefix">insert_invitation</i>{% endpart %} {% endform %} """)
def __init__(self, path, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['original'] = forms.FilePathField(path=path, recursive=True) self.fields['preview'] = forms.FilePathField(path=path, recursive=True, required=False)
class UploadFileForm(forms.Form): title = forms.CharField(max_length=50) file = forms.FileField() # upload_to='../test/data/user_handles/') t_h_canned = forms.FilePathField(path="./test/data/user_handles/") canned_field = forms.FilePathField( path="./test/data/abusive_terms/") #"smart/category/")
class CompareConfigForm(forms.Form): first_file_field = forms.FilePathField( path=f'{settings.MEDIA_ROOT}\\uploads\\', recursive=True, match=r'\.js(on)?$') second_file_field = forms.FilePathField( path=f'{settings.MEDIA_ROOT}\\uploads\\', recursive=True, match=r'\.js(on)?$')
class SignUpForm(UserCreationForm): username = forms.CharField(max_length=10, required=True, help_text='영문 10자로 입력하세요.', label='아이디') password1 = forms.CharField(max_length=12, widget=forms.PasswordInput, label='비밀번호', help_text='최대 12자로 입력하세요.') password2 = forms.CharField(max_length=12, widget=forms.PasswordInput, label='비밀번호 확인', help_text='비밀번호 확인') first_name = forms.CharField(max_length=8, required=True, help_text='길동', label='이름') last_name = forms.CharField(max_length=4, required=True, help_text='홍', label='성') fileName = forms.FilePathField(path='tutor_excel/', label="강사시간표 파일명") class Meta: model = User fields = ('username', 'password1', 'password2', 'first_name', 'last_name', 'fileName')
class ProjectDirInputForm(forms.Form): project_directory = forms.FilePathField( path=PROJECT_STORAGE, allow_files=False, allow_folders=True, label="Project Directory" )
class LoadXMLExample(forms.Form): schema_version = forms.ModelChoiceField( queryset=Schema.objects.all(), empty_label=None, to_field_name='version', initial=DEFAULT_SCHEMA_VERSION, widget=forms.Select(attrs={'id': 'schema_dropdown'})) file_name = forms.FilePathField( path=os.path.join(os.path.abspath(os.path.dirname(__file__)), 'lib', 'validator', 'examples'), recursive=True, match=r'\.xml$', allow_files=True, widget=forms.Select(attrs={'id': 'file_dropdown'})) form_type = forms.CharField(widget=forms.HiddenInput(), initial='example') def clean(self): super(LoadXMLExample, self).clean() # remove file_name error if 'file_name' in self._errors: for idx, i in enumerate(self._errors['file_name']): if 'Select a valid choice. bsyncviewer/lib/validator/examples/' in i: del self._errors['file_name'][idx] print("file_name errors now: {}".format(self._errors['file_name'])) return self.cleaned_data
class DjTestForm(forms.Form): t1=forms.CharField(required=True, label='name', widget=widgets.TextInput(attrs={'class':'t1','placeholder':'username'}), show_hidden_initial=True, initial='biubiu', validators=[RegexValidator(r'^[0-9]+$','pls input number',code='number')], disabled=False, label_suffix=':', max_length=8, min_length=2, strip=True, error_messages={'required':'not null','invalid':'format error','number':'must number','max_length':'too long'}) t2=forms.ChoiceField(choices=[(1,'hehe'),(2,'haha')]) t3=forms.IntegerField(widget=widgets.Select(choices=[])) #自动做类型转换 #t4=forms.FileField() t4=models_fields.ModelChoiceField(queryset=models.News.objects.all(),empty_label='Pls choose',to_field_name='id') t5=forms.TypedChoiceField( choices=[(1,'hehe'),(2,'biubiu'),], initial=2, coerce=lambda x:int(x) ) t6=forms.FilePathField(path='chouti/static', allow_folders=True, recursive=True) def __init__(self,*args,**kwargs): super(DjTestForm,self).__init__(*args,**kwargs) self.fields['t3'].widget.choices=models.News.objects.all().values_list('id','title')
class UserForm(forms.Form): name = forms.CharField(label="Имя") pswd = forms.CharField(label="Пароль", widget=forms.PasswordInput) tmp = forms.FilePathField( path="C:/hello_world/Python/try_django/first_try/hello/static/text/", label="Файл", help_text="выберите файл")
def __init__(self, *args, **kwargs): super(Search, self).__init__(*args, **kwargs) self.fields['playbook'] = forms.FilePathField( path=settings.ANSIBLE_PLAYBOOKS_PATH, match='.*\.yml$', required=False, widget=forms.Select(attrs={'class': 'need-select2'}))
class ManyFieldsExampleForm(forms.Form): hiddeninput = forms.CharField(widget=forms.HiddenInput()) multiplehiddeninput = forms.MultipleChoiceField(widget=forms.MultipleHiddenInput, choices=CONTINENTS) modelchoicefield = forms.ModelChoiceField(queryset=Friend.objects.all(), empty_label="Empty Space", to_field_name="first_name") modelchoicefield2 = forms.ModelChoiceField(queryset=Friend.objects.all(), to_field_name="first_name") modelmultiplechoicefield = forms.ModelMultipleChoiceField(queryset=Friend.objects.all()) booleanfield = forms.BooleanField(label="BooleanField") charfield = forms.CharField(label="CharField") choicefield = forms.ChoiceField(label="ChoiceField", choices=CONTINENTS) typedchoicefield = forms.TypedChoiceField(label="TypedChoiceField") datefield = forms.DateField(label="DateField") datetimefield = forms.DateTimeField(label="DateTimeField") decimalfield = forms.DecimalField(label="DecimalField") durationfield = forms.DurationField(label="DurationField") emailfield = forms.EmailField(label="EmailField") filefield = forms.FileField(label="FileField") filepathfield = forms.FilePathField(label="FilePathField", path="/") floatfield = forms.FloatField(label="FloatField") imagefield = forms.ImageField(label="ImageField") integerfield = forms.IntegerField(label="IntegerField") genericipaddressfield = forms.GenericIPAddressField(label="GenericIPAddressField") multiplechoicefield = forms.MultipleChoiceField(label="MultipleChoiceField", choices=CONTINENTS) typedmultiplechoicefield = forms.TypedMultipleChoiceField(label="TypedMultipleChoiceField", choices=CONTINENTS) nullbooleanfield = forms.NullBooleanField(label="NullBooleanField") slugfield = forms.SlugField(label="SlugField") timefield = forms.TimeField(label="TimeField") urlfield = forms.URLField(label="URLField") uuidfield = forms.UUIDField(label="UUIDField")
class Create(forms.ModelForm): template = forms.ModelChoiceField(queryset=models.TaskTemplate.objects.all(), required=False, widget=forms.Select(attrs={'class': 'need-select2'})) inventory = forms.FileField(required=False) hosts = forms.ModelMultipleChoiceField(queryset=models.Host.objects.order_by(Lower('name')), required=False, widget=forms.SelectMultiple(attrs={'class': 'need-select2'})) host_groups = forms.ModelMultipleChoiceField(queryset=models.HostGroup.objects.order_by(Lower('name')), required=False, widget=forms.SelectMultiple(attrs={'class': 'need-select2'})) playbook = forms.FilePathField(path=settings.ANSIBLE_PLAYBOOKS_PATH, match='.*\.yml$', widget=forms.Select(attrs={'class': 'need-select2'})) verbose = forms.ChoiceField(choices=consts.VERBOSE_CHOICES) ansible_user = forms.ModelChoiceField(queryset=models.AnsibleUser.objects.all(), widget=forms.Select(attrs={'class': 'need-select2'})) class Meta: model = models.Task fields = ('template', 'hosts', 'playbook', 'host_groups', 'ansible_user', 'verbose') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['ansible_user'].initial = models.AnsibleUser.objects.first() self.fields['playbook'] = forms.FilePathField(path=settings.ANSIBLE_PLAYBOOKS_PATH, match='.*\.yml$', widget=forms.Select(attrs={'class': 'need-select2'}))
class PersonalPathForm(forms.Form): """fichier dans le repertoire personnel d'export d'output""" _path = path.join(settings.WK_EXPORT_DIR, gi.roles) personal_files = forms.FilePathField(path=_path, match=project + '_.*', widget=SelectMultiple)
class addExperiment(forms.Form): experiment_name = forms.CharField(max_length=200, min_length=1) experiment_date = forms.DateField(widget=forms.widgets.DateInput( attrs={ 'type': 'date', })) conditions = forms.FilePathField(path='.')
def formfield_for_dbfield(self, db_field, **kwargs): if db_field.name == 'content': if settings.USE_ADMIN_AREA_TINYMCE: return db_field.formfield(widget=TinyMCE( attrs={ 'cols': 80, 'rows': 30 }, mce_attrs={ 'external_link_list_url': reverse('tinymce.views.flatpages_link_list') }, )) elif db_field.name == "template_name" and settings.USE_TEMPLATE_DROPDOWN: prev_field = super(FlatPageAdmin, self).formfield_for_dbfield(db_field, **kwargs) return forms.FilePathField( label=prev_field.label, path=settings.TEMPLATE_DIR, required=False, recursive=False, match=settings.TEMPLATE_FILES_REGEXP, ) return super(FlatPageAdmin, self).formfield_for_dbfield(db_field, **kwargs)
class SelectInputForm(forms.Form): choice_field = forms.ChoiceField( label='City', label_suffix=" : ", required=True, disabled=False, choices=city, widget=forms.Select(attrs={'class': 'form-control'}), error_messages={'required': "This field is required."}) typed_choice_field = forms.TypedChoiceField( label='City', label_suffix=" : ", required=True, disabled=False, choices=city, coerce=str, empty_value='', widget=forms.Select(attrs={'class': 'form-control'}), error_messages={'required': "This field is required."}) file_path_file = forms.FilePathField( label='File Path', label_suffix=" : ", required=True, disabled=False, path="django_form_fields/", recursive=True, allow_files=True, allow_folders=True, match="url.*", widget=forms.Select(attrs={'class': 'form-control'}), error_messages={'required': "This field is required."})
def __init__(self, request, *args, **kwargs): super(RecordingForm, self).__init__(*args, **kwargs) self.fields = add_placeholder_and_asterisk(self.fields) if self.initial.get("type"): self.fields['type'].widget = forms.HiddenInput() self.fields['source_file'] = forms.FilePathField( path=DEFAULT_RECORDER_PATH, recursive=True, label=_("source_file")) self.fields['source_file'].widget.attrs['class'] = 'form-control' self.fields["recorder"].queryset = self.fields["recorder"].queryset.\ filter( sites=Site.objects.get_current()) self.fields["user"].queryset = self.fields["user"].queryset.filter( owner__sites=Site.objects.get_current()) if not (check_show_user(request) or request.user.is_superuser or request.user.has_perm("recorder.add_recording")): del self.fields['user'] if not (request.user.is_superuser or request.user.has_perm("recorder.add_recording")): self.fields['recorder'].widget = forms.HiddenInput() self.fields['delete'].widget = forms.HiddenInput() self.fields['source_file'].widget = forms.HiddenInput()
class UseForm(forms.Form): name = forms.CharField(label='Имя', help_text='Веедите свое имя', required=False) text = forms.CharField(label="Фамилия", required=False) rr = forms.EmailField(label="Email", required=False) bb = forms.FilePathField(label="Дата", path="C:\Intel\Logs")
class ManyFieldsForm(forms.Form): booleanfield = forms.BooleanField() charfield = forms.CharField(max_length=40, null=True) datetimefield = forms.DateTimeField(auto_now_add=True) datefield = forms.DateField(auto_now_add=True) decimalfield = forms.DecimalField(max_digits=5, decimal_places=2) emailfield = forms.EmailField() filefield = forms.FileField(name='test_file', upload_to='test') filepathfield = forms.FilePathField(path='/some/path') floatfield = forms.FloatField() genericipaddressfield = forms.GenericIPAddressField() imagefield = forms.ImageField(name='test_image', upload_to='test') # note: IPAdressField has been deprecated since django 1.7 so might not # be available if using django 1.8+ ipaddressfield = getattr(forms, 'IPAddressField', 'GenericIPAddressField')() intfield = forms.IntegerField(null=True) nullbooleanfield = forms.NullBooleanField() slugfield = forms.SlugField() timefield = forms.TimeField() urlfield = forms.URLField() def boolean_field_tests(self): print(self.booleanfield | True) print(self.nullbooleanfield | True) def string_field_tests(self): print(self.charfield.strip()) print(self.charfield.upper()) print(self.charfield.replace('x', 'y')) print(self.filepathfield.strip()) print(self.filepathfield.upper()) print(self.filepathfield.replace('x', 'y')) print(self.emailfield.strip()) print(self.emailfield.upper()) print(self.emailfield.replace('x', 'y')) def datetimefield_tests(self): now = datetime.now() print(now - self.datetimefield) print(self.datetimefield.ctime()) def datefield_tests(self): now = date.today() print(now - self.datefield) print(self.datefield.isoformat()) def decimalfield_tests(self): print(self.decimalfield.adjusted()) def filefield_tests(self): print(self.filefield) print(self.imagefield) def numberfield_tests(self): print(self.intfield + 5)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['local_image'] = forms.FilePathField(label='Folder of images and masks', **local_file_args, allow_folders=True, allow_files=False) #self.fields['local_mask'] = forms.FilePathField(label='Local mask file (optional)', # **local_file_args, allow_folders=False) #self.fields['local_mask'] = None self.fields['local_image'].widget.attrs['class'] = 'form-control'
class ModifyForm(forms.Form): no = forms.CharField(max_length=20, strip=True, required=False) datasource = forms.CharField(max_length=50, strip=True, required=False) path = forms.FilePathField(path='.', widget=widgets.FileInput, allow_folders=False, required=False) # path 2019.8.6 sheet = forms.CharField(max_length=32, required=False)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['ansible_user'].initial = models.AnsibleUser.objects.first( ) self.fields['playbook'] = forms.FilePathField( path=settings.ANSIBLE_PLAYBOOKS_PATH, match='.*\.yml$', widget=forms.Select(attrs={'class': 'need-select2'}))
class ExtractForm(forms.Form): A4接口 = forms.BooleanField(initial=True) # option1 = forms.BooleanField(initial=True) # optionsRadios1 = forms.BooleanField(initial=True) A5接口 = forms.BooleanField(initial=True) 选择本地报文 = forms.BooleanField(initial=True) # LocalFile =forms. BooleanField(initial=True) filepath = forms.FilePathField(path="e://read.txt")
class SearchForm(forms.Form): uploaded = forms.FileField( required=False, allow_empty_file=False, widget=forms.ClearableFileInput(attrs={'multiple': True})) typed = forms.CharField(widget=forms.Textarea, required=False) category = forms.FilePathField(path="./test/data/abusive_terms/", required=False)
class UploadImageForm(forms.Form): """ upload image to static_dir """ static_image_path = os.path.join(getattr(settings, 'STATIC_ROOT'), 'image') image_dir = forms.FilePathField(path=static_image_path, recursive=True, allow_files=False, allow_folders=True, required=False) image_name = forms.CharField(max_length=32) image_file = forms.ImageField()
class ManyFieldsForm(forms.Form): booleanfield = forms.BooleanField(default=True) charfield = forms.CharField(max_length=40, null=True) datetimefield = forms.DateTimeField(auto_now_add=True) datefield = forms.DateField(auto_now_add=True) decimalfield = forms.DecimalField(max_digits=5, decimal_places=2) emailfield = forms.EmailField() filefield = forms.FileField(name='test_file', upload_to='test') filepathfield = forms.FilePathField() floatfield = forms.FloatField() genericipaddressfield = forms.GenericIPAddressField() imagefield = forms.ImageField(name='test_image', upload_to='test') ipaddressfield = forms.IPAddressField() intfield = forms.IntegerField(null=True) nullbooleanfield = forms.NullBooleanField() slugfield = forms.SlugField() timefield = forms.TimeField() urlfield = forms.URLField() def boolean_field_tests(self): print(self.booleanfield | True) print(self.nullbooleanfield | True) def string_field_tests(self): print(self.charfield.strip()) print(self.charfield.upper()) print(self.charfield.replace('x', 'y')) print(self.filepathfield.strip()) print(self.filepathfield.upper()) print(self.filepathfield.replace('x', 'y')) print(self.emailfield.strip()) print(self.emailfield.upper()) print(self.emailfield.replace('x', 'y')) def datetimefield_tests(self): now = datetime.now() print(now - self.datetimefield) print(self.datetimefield.ctime()) def datefield_tests(self): now = date.today() print(now - self.datefield) print(self.datefield.isoformat()) def decimalfield_tests(self): print(self.decimalfield.adjusted()) def filefield_tests(self): print(self.filefield) print(self.imagefield) def numberfield_tests(self): print(self.intfield + 5)
class UploadsForm(forms.Form): file_path = forms.FilePathField( '/root/aaa.xlsx', required=False, widget=forms.FileInput( attrs={ 'id': 'file_path', 'placeholder': 'please enter the keyword which you want to search', 'class': 'form-control' }))
class CurrentImageModelAdminForm(self.form): load = forms.FilePathField( label='выбрать', path=path, recursive=True, match='.+\.(jpg|png|gif)$(?i)', required=False, widget=forms.Select(attrs={ 'class': 'vSmallSelectField', }), )
class NewForm(forms.Form): no = forms.CharField(max_length=20, strip=True, required=True) case = forms.CharField(max_length=50, strip=True, required=True) # project = forms.ChoiceField(widget=widgets.Select, required=True) # project = forms.Select() # path = forms.FileInput() path = forms.FilePathField(path='.', widget=widgets.FileInput, allow_folders=False, required=False) # path 2019.8.6 sheet = forms.CharField(max_length=32, required=False)
def __init__(self, *args, **kwargs): super(PcapForm, self).__init__(*args, **kwargs) self.fields['filepath'] = forms.FilePathField(label='Select pcap file', path=settings.PCAP_FOLDER, recursive=True, match="\.pcap$", allow_files=True, allow_folders=False, required=True) origin_description = forms.CharField(label='Origin description', required=True)