class ImageForm(ModelForm, ImageValidationMixin): hdr_file = FileField( required=False, label='.hdr part of the map (if applicable)', widget=AdminResubmitFileWidget) def __init__(self, *args, **kwargs): ImageValidationMixin.__init__(self, *args, **kwargs) ModelForm.__init__(self, *args, **kwargs) self.helper = FormHelper(self) self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-lg-2' self.helper.field_class = 'col-lg-10' self.helper.form_tag = False self.helper.form_method = 'post' self.helper.add_input(Submit('submit', 'Submit')) class Meta: model = Image exclude = [] widgets = { 'file': AdminResubmitFileWidget, 'hdr_file': AdminResubmitFileWidget, 'data_origin': HiddenInput } def clean(self, **kwargs): cleaned_data = super(ImageForm, self).clean() cleaned_data["tags"] = clean_tags(cleaned_data) return self.clean_and_validate(cleaned_data)
class LevelSerializer(serializers.ModelSerializer): file = FileField() class Meta: fields = ( 'id', 'level', 'answer', 'source_hint', ) model = Level
class DocumentForm(forms.ModelForm): file = FileField(required=False) def clean_file(self): value = self.cleaned_data["file"] if str(value).split('.')[1].lower() != 'stp': raise forms.ValidationError('Not Supported') return 'False' class Meta: model = Document fields = ('description', )
class LevelSerializer(serializers.ModelSerializer): file = FileField() hints = HintSerializer(many=True) class Meta: fields = ( 'id', 'level', 'level_file', 'source_hint', 'filetype', 'hints', ) model = Level
class PostingForm(ModelForm): #사용자가 업로드할 파일/이미지를 입력받는 공간 생성 #forms.ImageField : 사용자가 이미지를 선택할 수 있는 입력공간 #required : forms.xxField의 공용 매개변수 #required : 사용자가 꼭 입력하지 않아도 되는 설정을 하는 매개변수 #ClearableFileInput : <input type='file'>형태의 입력공간에 파일 관련 추가설정을 할 수 있는 위젯 #multiple : True -> 하나의 입력공간에 여러개의 파일을 선택할 수 있도록 허용 images = ImageField(required=False, widget=ClearableFileInput(attrs={'multiple': True})) files = FileField(required=False, widget=ClearableFileInput(attrs={'multiple': True})) class Meta: model = Post fields = ['category', 'title', 'content']
def __init__(self, upload_to='', path='', match='', recursive=False, widget=None, initial=None, optional=False, *args, **kwargs): self.upload_to, self.path, self.match, \ self.recursive, self.initial, self.optional = \ upload_to, path, match, recursive, initial, optional self.max_length = kwargs.pop('max_length', None) self.required = getattr(kwargs, 'required', True) fields = ( FilePathField( path=self.path, match=self.match, recursive=self.recursive, initial=self.initial, required=self.required, ), FileField( max_length=self.max_length, initial=self.initial, required=self.required, ), ) widget = widget or self.widget if isinstance(widget, type): widget = widget() self.widget = widget super(FileSelectOrUploadField, self).__init__(fields, widget=self.widget, *args, **kwargs) self.choices = [('', 'Use upload')] + fields[0].choices self.widget.is_required = self.required
class UploadFileForm(Form): # TODO Need to upload in a temp directory # (upload_to="images/%s/%s"%(instance.collection.id, filename)) file = FileField(required=False) def __init__(self, *args, **kwargs): super(UploadFileForm, self).__init__(*args, **kwargs) self.file = '' def clean(self): cleaned_data = super(UploadFileForm, self).clean() file = cleaned_data.get("file") if file: ext = os.path.splitext(file.name)[1] ext = ext.lower() if ext not in ['.zip', '.gz']: raise ValidationError("Not allowed filetype!")
def __init__(self, to=None, *args, **kwargs): """ Accepts EITHER a file or an URL. The `to` parameter accepts 3 values: None: default to_python, returns either url or file 'file': if an url is submited, download it into an inmemory object 'url': uploads the file to default storage and returns the URL The`upload_to` param must be set when to='url' if using AWS, set no_aws_qs to disable querystring auth """ self.to = to self.no_aws_qs = kwargs.pop('no_aws_qs', False) if 'upload_to' in kwargs: self.upload_to = kwargs.pop('upload_to') elif self.to == 'url': raise RuntimeError('If normalizing to an URL `upload_to` ' 'must be set') fields = (FileField(), URLField()) super(FileOrURLField, self).__init__(fields, *args, **kwargs)
class PostingForm(ModelForm): #사용자가 업로드할 파일/이미지를 입력받는 공간 생성 #import시 주의 사항 forms에 있는 ImageField import할것! #forms.ImageField : 사용자가 이미지를 선택할 수 잇는 입력공간 #required : formsXXField의 공용 매개 변수로 사용자가 꼭 입력하지 않아도 되는 설정을 하는 매개변수 #여러개를 동시에 입력할 수 있게 하려면 위젯을 달아주면 된다. #ClearableFileInput : <input type ='file' 형태의 입력공간에 # 파일관련 추가설정을 할 수 있는 위젯 #multiple : True -> 하나의 입력공간에 여러개의 파일을 선택할 수 있도록 허용 images = ImageField(required=False, widget=ClearableFileInput(attrs={'multiple': True})) #forms.ImageField()로 해도 된다. #더블클릭해서 ClearableFileInput import #form class에 있는 FileField import files = FileField(required=False, widget=ClearableFileInput(attrs={'multiple': True})) class Meta: model = Post fields = ['category', 'title', 'content'] #사용자에게 입력 받을 것들
class EditUserForm2(ModelForm): img_1 = FileField(required=False, label="Imagen 1", max_length=1024) email_2 = forms.EmailField( widget=forms.TextInput(attrs={'placeholder': HINT_EMAIL_2}), max_length=90, required=False) phone_1 = forms.CharField( widget=forms.TextInput(attrs={'placeholder': HINT_PHONE_1}), max_length=30, required=False) phone_2 = forms.CharField( widget=forms.TextInput(attrs={'placeholder': HINT_PHONE_2}), max_length=30, required=False) def __init__(self, *args, **kwargs): super(EditUserForm2, self).__init__(*args, **kwargs) self.fields['art'].label = TASTE_ART self.fields['music'].label = TASTE_MUSIC self.fields['tech'].label = TASTE_TECH self.fields['cars'].label = TASTE_CARS self.fields['travels'].label = TASTE_TRAVELS self.fields['clothes'].label = TASTE_CLOTHES self.fields['cine'].label = TASTE_CINE self.fields['sports'].label = TASTE_SPORTS self.fields['eco'].label = TASTE_ECO self.fields['culture'].label = TASTE_CULTURE self.fields['spectacles'].label = TASTE_SPECTACLES self.fields['love'].label = TASTE_LOVE self.fields['food'].label = TASTE_FOOD self.fields['vacations'].label = TASTE_VACATIONS self.fields['services'].label = TASTE_SERVICES class Meta: model = UserProfile fields = ('city', 'email_2', 'phone_1', 'phone_2', 'art', 'music', 'tech', 'cars', 'travels', 'clothes', 'cine', 'sports', 'eco', 'culture', 'spectacles', 'love', 'food', 'vacations', 'services', 'lang')
class ImageForm(ModelForm, ImageValidationMixin): hdr_file = FileField(required=False, label='.hdr part of the map (if applicable)', widget=AdminResubmitFileWidget) def __init__(self, *args, **kwargs): ImageValidationMixin.__init__(self, *args, **kwargs) ModelForm.__init__(self, *args, **kwargs) self.helper = FormHelper(self) self.helper.form_class = 'form-horizontal' self.helper.form_tag = False class Meta: model = Image exclude = [] widgets = { 'file': AdminResubmitFileWidget, 'hdr_file': AdminResubmitFileWidget } def clean(self, **kwargs): cleaned_data = super(ImageForm, self).clean() cleaned_data["tags"] = clean_tags(cleaned_data) return self.clean_and_validate(cleaned_data)
class RecipeImportForm(Form): file = FileField() filetype = ChoiceField(choices=(("beerxml", "BeerXML"), ("json", "JSON")))
def __init__(self, path, user, *args, **kwargs): super(DynForm, self).__init__(*args, **kwargs) pathComplete = str(path) elements = pathComplete.split("/") studyName = elements[2] stageName = elements[3] for study in Study.objects.filter(studyName=str(studyName)): tempEntity = [] for entity in Patient.objects.filter( studyId__idStudy=study.idStudy, userOwner=user): tempLabel = str(entity).split(" ") patientLabel = tempLabel[0] + ". ID: " + tempLabel[1] tempEntity.append((patientLabel, patientLabel)) choiceEnt = tuple(tempEntity) self.fields['Paciente'] = ChoiceField( tempEntity, initial=tempEntity[len(tempEntity) - 1]) self.fields['Paciente'].widget.attrs['class'] = 'form-control' for stage in Stage.objects.filter(studyId=study.idStudy): if stage.stageType == str(stageName): questionList = [] for questionGroups in Question_Groups.objects.filter( groupStage__idStage=stage.idStage).order_by( 'order'): for question in questionGroups.idQuestions.all(): questionList.append(question) for question in questionList: if question.questionsType == 'Char': self.fields['%s' % question] = CharField( max_length=255, required=False) self.fields['%s' % question].label = str( question.questionsLabel) self.fields['%s' % question].help_text = str( question.questionHelp) self.fields['%s' % question].widget.attrs[ 'class'] = 'form-control' if question.questionsType == 'Int': self.fields['%s' % question] = IntegerField( widget=forms.NumberInput(), required=False) self.fields['%s' % question].label = str( question.questionsLabel) self.fields['%s' % question].help_text = str( question.questionHelp) self.fields['%s' % question].widget.attrs[ 'class'] = 'form-control' self.fields['%s' % question].widget.attrs[ 'min'] = question.questionMin self.fields['%s' % question].widget.attrs[ 'max'] = question.questionMax self.fields['%s' % question].widget.attrs['step'] = 1 if question.questionsType == 'Real': self.fields['%s' % question] = FloatField( widget=forms.NumberInput(), required=False) self.fields['%s' % question].label = str( question.questionsLabel) self.fields['%s' % question].help_text = str( question.questionHelp) self.fields['%s' % question].widget.attrs[ 'class'] = 'form-control' self.fields['%s' % question].widget.attrs[ 'min'] = question.questionMin self.fields['%s' % question].widget.attrs[ 'max'] = question.questionMax self.fields[ '%s' % question].widget.attrs['step'] = 0.1 if question.questionsType == 'Date': self.fields['%s' % question] = DateField( widget=forms.DateInput(), required=False) self.fields['%s' % question].label = str( question.questionsLabel) self.fields['%s' % question].help_text = str( question.questionHelp) self.fields['%s' % question].widget.attrs[ 'class'] = 'form-control' if question.questionsType == 'Time': self.fields['%s' % question] = TimeField( widget=forms.TimeInput(), required=False) self.fields['%s' % question].label = str( question.questionsLabel) self.fields['%s' % question].help_text = str( question.questionHelp) self.fields['%s' % question].widget.attrs[ 'class'] = 'form-control' if question.questionsType == 'Bool': self.fields[ '%s' % question] = NullBooleanField( widget=forms.NullBooleanSelect(), required=False) self.fields['%s' % question].label = str( question.questionsLabel) self.fields['%s' % question].help_text = str( question.questionHelp) self.fields['%s' % question].widget.attrs.update({ 'onclick': "toggle_id_%s()" % question, }) self.fields['%s' % question].widget.attrs[ 'class'] = 'form-control' if question.questionsType == 'Img': self.fields['%s' % question] = FileField( required=False) self.fields['%s' % question].label = str( question.questionsLabel) self.fields['%s' % question].help_text = str( question.questionHelp) self.fields['%s' % question].widget.attrs[ 'class'] = 'form-control' if question.questionsType == 'Enum': choices = Choices.objects.filter( questionId__questionsId=question. questionsId) list_of_choices = [] for choice in choices: list_of_choices.append((choice, choice)) tuple_of_choices = tuple(list_of_choices) self.fields['%s' % question] = ChoiceField( widget=forms.Select(), choices=tuple_of_choices, required=False) self.fields['%s' % question].label = str( question.questionsLabel) self.fields['%s' % question].help_text = str( question.questionHelp) self.fields['%s' % question].widget.attrs.update({ 'onchange': "toggle_id_%s()" % question, }) self.fields['%s' % question].widget.attrs[ 'class'] = 'form-control'
class ProfilePicForm(forms.Form): file = FileField(required=False)
class ValidationForm(forms.Form): filename = FileField(label='Selecteer Excel bestand(en)')
def __init__(self, *args, **kwargs): fields = ( FileField(), URLField(), ) super(FileOrUrlField, self).__init__(fields, *args, **kwargs)
class SubjectUploadForm(Form): error_css_class = 'error' required_css_class = 'required' file = FileField(label='Import Subjects')
class UploadFileForm(forms.Form): filename = FileField(label='Selecteer Excel bestand(en)')
class LevelSerializer(serializers.ModelSerializer): file = FileField() class Meta: fields = ('id', 'level', 'level_file', 'source_hint', 'filetype') model = Level
class UploadFileForm(djangoforms.ModelForm): file = FileField()
class UCForm(Form): social = SelectMultiple(choices=SOCIALS_ENUM) links = FileField()
class BatchImportForm(Form): json_file = FileField()
class ImageForm(ModelForm): hdr_file = FileField(required=False, label='.hdr part of the map (if applicable)', widget=AdminResubmitFileWidget) def __init__(self, *args, **kwargs): super(ImageForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_class = 'form-horizontal' self.helper.form_tag = False self.afni_subbricks = [] self.afni_tmp = None class Meta: model = Image exclude = [] widgets = { 'file': AdminResubmitFileWidget, 'hdr_file': AdminResubmitFileWidget, } def clean(self, **kwargs): cleaned_data = super(ImageForm, self).clean() file = cleaned_data.get("file") if file: # check extension of the data file _, fname, ext = split_filename(file.name) if not ext.lower() in [".nii.gz", ".nii", ".img"]: self._errors["file"] = self.error_class(["Doesn't have proper extension"]) del cleaned_data["file"] return cleaned_data # prepare file to loading into memory file.open() if file.name.lower().endswith(".gz"): fileobj = GzipFile(filename=file.name, mode='rb', fileobj=file.file) else: fileobj=file.file file_map = {'image': nb.FileHolder(file.name, fileobj)} try: tmp_dir = tempfile.mkdtemp() if ext.lower() == ".img": hdr_file = cleaned_data.get('hdr_file') if hdr_file: # check extension of the hdr file _, _, hdr_ext = split_filename(hdr_file.name) if not hdr_ext.lower() in [".hdr"]: self._errors["hdr_file"] = self.error_class( ["Doesn't have proper extension"]) del cleaned_data["hdr_file"] return cleaned_data else: hdr_file.open() file_map["header"] = nb.FileHolder(hdr_file.name, hdr_file.file) else: self._errors["hdr_file"] = self.error_class( [".img file requires .hdr file"]) del cleaned_data["hdr_file"] return cleaned_data # check if it is really nifti try: print file_map if "header" in file_map: nii = nb.Nifti1Pair.from_file_map(file_map) else: nii = nb.Nifti1Image.from_file_map(file_map) except Exception as e: raise self._errors["file"] = self.error_class([str(e)]) del cleaned_data["file"] return cleaned_data # detect AFNI 4D files and prepare 3D slices if nii is not None and detect_afni4D(nii): self.afni_subbricks = split_afni4D_to_3D(nii) else: squeezable_dimensions = len(filter(lambda a: a not in [0,1], nii.shape)) if squeezable_dimensions != 3: self._errors["file"] = self.error_class(["4D files are not supported.\n If it's multiple maps in one file please split them and upload separately"]) del cleaned_data["file"] return cleaned_data # convert to nii.gz if needed if ext.lower() != ".nii.gz" or squeezable_dimensions < len(nii.shape): #convert pseudo 4D to 3D if squeezable_dimensions < len(nii.shape): new_data = np.squeeze(nii.get_data()) nii = nb.Nifti1Image(new_data, nii.get_affine(), nii.get_header()) #Papaya does not handle float64, but by converting files we loose precision #if nii.get_data_dtype() == np.float64: #ii.set_data_dtype(np.float32) new_name = fname + ".nii.gz" nii_tmp = os.path.join(tmp_dir, new_name) nb.save(nii, nii_tmp) cleaned_data['file'] = memory_uploadfile(nii_tmp, new_name, cleaned_data['file']) finally: try: if self.afni_subbricks: self.afni_tmp = tmp_dir # keep temp dir for AFNI slicing else: shutil.rmtree(tmp_dir) except OSError as exc: if exc.errno != 2: # code 2 - no such file or directory raise # re-raise exception else: raise ValidationError("Couldn't read uploaded file") return cleaned_data