def create_document_field(self, field, options): return FileField(**options)
class ImportData(Form): data = FileField(label=u'Fichier avec les données')
class FileForm(Form): file1 = FileField()
class AssetImportForm(Form): assets_csv = FileField()
class IfcModifyForm(Form): name = CharField(required=False, min_length=1, max_length=100) ifc_file = FileField(required=False, validators=[IfcModel.validate_ifc_file])
def test_file_picklable(self): self.assertIsInstance(pickle.loads(pickle.dumps(FileField())), FileField)
def test_disabled_has_changed(self): f = FileField(disabled=True) self.assertIs(f.has_changed('x', 'y'), False)
class BatchForm(ModelForm): csv_file = FileField(label='CSV File') # Allow a form to be submitted without an 'allotted_assignment_time' # field. The default value for this field will be used instead. # See also the function clean_allotted_assignment_time(). allotted_assignment_time = IntegerField(initial=Batch._meta.get_field( 'allotted_assignment_time').get_default(), required=False) def __init__(self, *args, **kwargs): super(BatchForm, self).__init__(*args, **kwargs) self.fields[ 'allotted_assignment_time'].label = 'Allotted assignment time (hours)' self.fields['allotted_assignment_time'].help_text = 'If a user abandons a Task, ' + \ 'this determines how long it takes until their assignment is deleted and ' + \ 'someone else can work on the Task.' self.fields['csv_file'].help_text = 'You can Drag-and-Drop a CSV file onto this ' + \ 'window, or use the "Choose File" button to browse for the file' self.fields['csv_file'].widget = CustomButtonFileWidget() self.fields['project'].label = 'Project' self.fields['name'].label = 'Batch Name' # csv_file field not required if changing existing Batch # # When changing a Batch, the BatchAdmin.get_fields() # function will cause the form to be rendered without # displaying an HTML form field for the csv_file field. I was # running into strange behavior where Django would still try # to validate the csv_file form field, even though there was # no way for the user to provide a value for this field. The # two lines below prevent this problem from occurring, by # making the csv_file field optional when changing # a Batch. if not self.instance._state.adding: self.fields['csv_file'].required = False self.fields['project'].widget = \ ProjectNameReadOnlyWidget(self.instance.project) def clean(self): """Verify format of CSV file Verify that: - fieldnames in CSV file are identical to fieldnames in Project - number of fields in each row matches number of fields in CSV header """ cleaned_data = super(BatchForm, self).clean() csv_file = cleaned_data.get("csv_file", False) project = cleaned_data.get("project") if not csv_file or not project: return validation_errors = [] rows = unicodecsv.reader(csv_file) header = next(rows) csv_fields = set(header) template_fields = set(project.fieldnames) if csv_fields != template_fields: template_but_not_csv = template_fields.difference(csv_fields) if template_but_not_csv: validation_errors.append( ValidationError( 'The CSV file is missing fields that are in the HTML template. ' 'These missing fields are: %s' % ', '.join(template_but_not_csv))) expected_fields = len(header) for (i, row) in enumerate(rows): if len(row) != expected_fields: validation_errors.append( ValidationError( 'The CSV file header has %d fields, but line %d has %d fields' % (expected_fields, i + 2, len(row)))) if validation_errors: raise ValidationError(validation_errors) # Rewind file, so it can be re-read csv_file.seek(0) def clean_allotted_assignment_time(self): """Clean 'allotted_assignment_time' form field - If the allotted_assignment_time field is not submitted as part of the form data (e.g. when interacting with this form via a script), use the default value. - If the allotted_assignment_time is an empty string (e.g. when submitting the form using a browser), raise a ValidationError """ data = self.data.get('allotted_assignment_time') if data is None: return Batch._meta.get_field( 'allotted_assignment_time').get_default() elif data.strip() is u'': raise ValidationError('This field is required.') else: return data
class UploadFileForm(forms.Form): op = "upload" # The "hdfs" prefix in "hdfs_file" triggers the HDFSfileUploadHandler hdfs_file = FileField(forms.Form, label=_("File to Upload")) dest = PathField(label=_("Destination Path"), help_text=_("Filename or directory to upload to.")) extract_archive = BooleanField(required=False)
class ImportForm(Form): file = FileField()
class ImageForm(Form): file = FileField()
class ZIPImportForm(Form): zipfile = FileField(required=True, label="ZIP-файл")
class ForeignImportForm(Form): csv = FileField(required=True)
class EDRImportForm(Form): csv = FileField(required=True) is_state_companies = BooleanField( required=False, help_text="Керівники усіх компанії з файлу є ПЕПами")
class LDAPForm(ModelForm): ldap_certfile = FileField(label=_("Certificate"), required=False) advanced_fields = [ 'ldap_anonbind', 'ldap_usersuffix', 'ldap_groupsuffix', 'ldap_passwordsuffix', 'ldap_machinesuffix', 'ldap_sudosuffix', 'ldap_use_default_domain', 'ldap_kerberos_realm', 'ldap_kerberos_keytab', 'ldap_ssl', 'ldap_certfile', 'ldap_idmap_backend' ] class Meta: fields = '__all__' exclude = ['ldap_idmap_backend_type'] model = models.LDAP widgets = { 'ldap_bindpw': forms.widgets.PasswordInput(render_value=True), } def __init__(self, *args, **kwargs): super(LDAPForm, self).__init__(*args, **kwargs) self.fields["ldap_enable"].widget.attrs["onChange"] = ( "ldap_mutex_toggle();") def clean_ldap_certfile(self): filename = "/data/ldap_certfile" ldap_certfile = self.cleaned_data.get("ldap_certfile", None) if ldap_certfile and ldap_certfile != filename: if hasattr(ldap_certfile, 'temporary_file_path'): shutil.move(ldap_certfile.temporary_file_path(), filename) else: with open(filename, 'wb+') as f: for c in ldap_certfile.chunks(): f.write(c) f.close() os.chmod(filename, 0400) self.instance.ldap_certfile = filename return filename def clean_bindpw(self): cdata = self.cleaned_data if not cdata.get("ldap_bindpw"): cdata["ldap_bindpw"] = self.instance.ldap_bindpw binddn = cdata.get("ldap_binddn") bindpw = cdata.get("ldap_bindpw") hostname = cdata.get("ldap_hostname") errors = [] ret = FreeNAS_LDAP.validate_credentials(hostname, binddn=binddn, bindpw=bindpw, errors=errors) if ret is False: raise forms.ValidationError("%s." % errors[0]) def save(self): enable = self.cleaned_data.get("ldap_enable") started = notifier().started("ldap") super(LDAPForm, self).save() if enable: if started is True: started = notifier().restart("ldap") if started is False: started = notifier().start("ldap") if started is False: self.instance.ad_enable = False super(LDAPForm, self).save() raise ServiceFailed("ldap", _("LDAP failed to reload.")) else: if started == True: started = notifier().stop("ldap")
class UploadArchiveForm(forms.Form): op = "upload" archive = FileField(forms.Form, label=_("Archive to Upload")) dest = PathField(label=_("Destination Path"), help_text=_("Archive to upload to."))
class ImportForm(Form): upload = FileField()
class KerberosKeytabCreateForm(ModelForm): keytab_file = FileField(label=_("Kerberos Keytab"), required=False) class Meta: fields = '__all__' model = models.KerberosKeytab def clean_keytab_file(self): keytab_file = self.cleaned_data.get("keytab_file", None) if not keytab_file: raise forms.ValidationError(_("A keytab is required.")) encoded = None if hasattr(keytab_file, 'temporary_file_path'): filename = keytab_file.temporary_file_path() with open(filename, "rb") as f: keytab_contents = f.read() encoded = base64.b64encode(keytab_contents).decode() else: filename = tempfile.mktemp(dir='/tmp') with open(filename, 'wb+') as f: for c in keytab_file.chunks(): f.write(c) with open(filename, "rb") as f: keytab_contents = f.read() encoded = base64.b64encode(keytab_contents).decode() os.unlink(filename) return encoded def save_principals(self, keytab): if not keytab: return False keytab_file = self.cleaned_data.get("keytab_file") regex = re.compile( '^(\d+)\s+([\w-]+(\s+\(\d+\))?)\s+([^\s]+)\s+([\d+\-]+)(\s+)?$') tmpfile = tempfile.mktemp(dir="/tmp") with open(tmpfile, 'wb') as f: decoded = base64.b64decode(keytab_file) f.write(decoded) (res, out, err) = run("/usr/sbin/ktutil -vk '%s' list" % tmpfile) if res != 0: log.debug("save_principals(): %s", err) os.unlink(tmpfile) return False os.unlink(tmpfile) ret = False out = out.splitlines() if not out: return False for line in out: line = line.strip() if not line: continue m = regex.match(line) if m: try: kp = models.KerberosPrincipal() kp.principal_keytab = keytab kp.principal_version = int(m.group(1)) kp.principal_encryption = m.group(2) kp.principal_name = m.group(4) kp.principal_timestamp = m.group(5) kp.save() ret = True except Exception as e: log.debug("save_principals(): %s", e, exc_info=True) ret = False return ret def save(self): obj = super(KerberosKeytabCreateForm, self).save() if not self.save_principals(obj): obj.delete() log.debug("save(): unable to save principals") notifier().start("ix-kerberos")
def test_filefield_3(self): f = FileField(allow_empty_file=True) self.assertIsInstance(f.clean(SimpleUploadedFile('name', b'')), SimpleUploadedFile)
class QueryBuilderForm(forms.Form): """ Form to build an SQL query using a web interface. Works hand in hand with ``querybuilder.js`` on the client side; q.v. """ database = CharField(label="Schema", required=False) schema = CharField(label="Schema", required=True) table = CharField(label="Table", required=True) column = CharField(label="Column", required=True) datatype = CharField(label="Data type", required=True) offer_where = BooleanField(label="Offer WHERE?", required=False) # BooleanField generally needs "required=False", or you can't have False! where_op = CharField(label="WHERE comparison", required=False) date_value = DateField(label="Date value (e.g. 1900-01-31)", required=False) int_value = IntegerField(label="Integer value", required=False) float_value = FloatField(label="Float value", required=False) string_value = CharField(label="String value", required=False) file = FileField(label="File (for IN)", required=False) def __init__(self, *args, **kwargs) -> None: self.file_values_list = [] # type: List[Any] super().__init__(*args, **kwargs) def get_datatype(self) -> Optional[str]: return self.data.get('datatype', None) def is_datatype_unknown(self) -> bool: return self.get_datatype() == QB_DATATYPE_UNKNOWN def offering_where(self) -> bool: if self.is_datatype_unknown(): return False return self.data.get('offer_where', False) def get_value_fieldname(self) -> str: datatype = self.get_datatype() if datatype == QB_DATATYPE_INTEGER: return "int_value" if datatype == QB_DATATYPE_FLOAT: return "float_value" if datatype == QB_DATATYPE_DATE: return "date_value" if datatype in QB_STRING_TYPES: return "string_value" if datatype == QB_DATATYPE_UNKNOWN: return "" raise ValueError("Invalid field type") def get_cleaned_where_value(self) -> Any: # Only call this if you've already cleaned/validated the form! return self.cleaned_data[self.get_value_fieldname()] def clean(self) -> None: # Check the WHERE information is sufficient. if 'submit_select' in self.data or 'submit_select_star' in self.data: # Form submitted via the "Add" method, so no checks required. # http://stackoverflow.com/questions/866272/how-can-i-build-multiple-submit-buttons-django-form # noqa return if not self.offering_where(): return cleaned_data = super().clean() if not cleaned_data['where_op']: self.add_error('where_op', forms.ValidationError("Must specify comparison")) # No need for a value for NULL-related comparisons. But otherwise: where_op = cleaned_data['where_op'] if where_op not in SQL_OPS_VALUE_UNNECESSARY + SQL_OPS_MULTIPLE_VALUES: # Can't take 0 or many parameters, so need the standard single # value: value_fieldname = self.get_value_fieldname() value = cleaned_data.get(value_fieldname) if not value: self.add_error( value_fieldname, forms.ValidationError("Must specify WHERE condition")) # --------------------------------------------------------------------- # Special processing for file upload operations # --------------------------------------------------------------------- if where_op not in SQL_OPS_MULTIPLE_VALUES: return fileobj = cleaned_data['file'] # ... is an instance of InMemoryUploadedFile if not fileobj: self.add_error('file', forms.ValidationError("Must specify file")) return datatype = self.get_datatype() if datatype in QB_STRING_TYPES: form_to_python_fn = str elif datatype == QB_DATATYPE_DATE: form_to_python_fn = html_form_date_to_python elif datatype == QB_DATATYPE_INTEGER: form_to_python_fn = int_validator elif datatype == QB_DATATYPE_FLOAT: form_to_python_fn = float_validator else: # Safe defaults form_to_python_fn = str # Or: http://www.dabeaz.com/generators/Generators.pdf self.file_values_list = [] # type: List[Any] for line in fileobj.read().decode("utf8").splitlines(): raw_item = line.strip() if not raw_item or raw_item.startswith('#'): continue try: value = form_to_python_fn(raw_item) except (TypeError, ValueError): self.add_error('file', forms.ValidationError( f"File contains bad value: {raw_item!r}")) return self.file_values_list.append(value) if not self.file_values_list: self.add_error('file', forms.ValidationError( "No values found in file"))
class PBIUploadForm(Form): pbifile = FileField( label=_("PBI file to be installed"), help_text=_( "Click here to find out what PBI's are!" "<a href='http://www.pcbsd.org/en/package-management/' " "onclick='window.open(this.href);return false;'>" ), required=True ) def __init__(self, *args, **kwargs): self.jail = None if kwargs and 'jail' in kwargs: self.jail = kwargs.pop('jail') super(PBIUploadForm, self).__init__(*args, **kwargs) if self.jail: self.fields['pjail'] = forms.ChoiceField( label=_("Plugin Jail"), help_text=_("The plugin jail that the PBI is to be installed in."), choices=( (self.jail.jail_host, self.jail.jail_host), ), widget=forms.Select(attrs={ 'class': ( 'requireddijitDisabled dijitTextBoxDisabled ' 'dijitValidationTextBoxDisabled' ), 'readonly': True, }), required=False, ) def clean(self): cleaned_data = self.cleaned_data filename = '/var/tmp/firmware/pbifile.pbi' if cleaned_data.get('pbifile'): if hasattr(cleaned_data['pbifile'], 'temporary_file_path'): shutil.move( cleaned_data['pbifile'].temporary_file_path(), filename ) else: with open(filename, 'wb+') as sp: for c in cleaned_data['pbifile'].chunks(): sp.write(c) else: self._errors["pbifile"] = self.error_class([ _("This field is required."), ]) return cleaned_data def done(self, *args, **kwargs): newplugin = [] pjail = self.cleaned_data.get('pjail') jail = None if not pjail: #FIXME: Better base name, using pbi_info try: jail = new_default_plugin_jail("customplugin") except Exception as e: raise MiddlewareError(e) pjail = jail.jail_host if notifier().install_pbi(pjail, newplugin): newplugin = newplugin[0] notifier()._restart_plugins( jail=newplugin.plugin_jail, plugin=newplugin.plugin_name, ) elif jail: jail.delete()
class FormWithFile(Form): username = CharField() file = FileField()
class MeetingReportForm(Form): num = IntegerField(widget=HiddenInput()) title = CharField(label=u'Titre',widget=TextInput(attrs={'readonly': 'readonly', })) when = CharField(label=u'Date',widget=TextInput(attrs={'readonly': 'readonly', })) report = FileField(label='Compte rendu') send = BooleanField(label='Envoi du compte rendu aux membres',required=False)
class UserPerfilForm(ModelForm): clave_rh = CharField( label="Clave de empleado:", widget=TextInput( attrs={'class': 'form-control input-xs', 'readonly': 'True'} ) ) clave_jde = CharField( label="Clave de JDE:", widget=TextInput( attrs={'class': 'form-control input-xs', 'readonly': 'True'} ) ) fecha_nacimiento = CharField( label='Fecha de nacimiento', widget=DateInput( attrs={'class': 'form-control input-xs', 'data-date-format': 'yyyy-mm-dd', 'readonly': 'True'} ), ) foto = FileField( label="Foto", widget=ClearableFileInput( attrs={'class': 'dropzone dz-clickable dz-started'} ), ) class Meta: model = User fields = [ 'first_name', 'last_name', 'email', 'clave_rh', 'clave_jde', 'fecha_nacimiento', 'foto', ] labels = { 'first_name': 'Nombre', 'last_name': 'Apellidos', 'email': 'Email', 'clave_rh': 'Clave de empleado', 'clave_jde': 'Clave de JDE', 'fecha_nacimiento': 'Fecha de nacimiento', 'foto': 'Foto', } widgets = { 'first_name': TextInput(attrs={'class': 'form-control input-xs', 'readonly': 'True'}), 'last_name': TextInput(attrs={'class': 'form-control input-xs', 'readonly': 'True'}), 'email': TextInput(attrs={'class': 'form-control input-xs'}), } def __init__(self, *args, **kwargs): super(UserPerfilForm, self).__init__(*args, **kwargs) self.fields['clave_jde'].required = False self.fields['fecha_nacimiento'].required = False self.fields['foto'].required = False
class IfcForm(Form): name = CharField(min_length=1, max_length=100) ifc_file = FileField(validators=[IfcModel.validate_ifc_file])
class UserRegistroForm(UserCreationForm): clave_rh = ChoiceField( label="Id Empleado", widget=Select( attrs={'class': 'form-control input-xs'} ) ) clave_jde = CharField( label="Clave de JDE", widget=HiddenInput() ) foto = FileField( label="Foto", widget=ClearableFileInput( attrs={'class': 'dropzone dz-clickable dz-started'} ), ) password1 = CharField( label="Contraseña", widget=PasswordInput( attrs={'class': 'form-control input-xs'} ) ) password2 = CharField( label="Confirmar Contraseña", widget=PasswordInput( attrs={'class': 'form-control input-xs'} ) ) rfc = CharField( label="RFC", widget=TextInput( attrs={'class': 'form-control input-xs'} ) ) fecha_nacimiento = DateField( widget=HiddenInput() ) accept_terms = BooleanField( widget=CheckboxInput() ) class Meta: model = User fields = [ 'username', 'first_name', 'last_name', 'email', 'clave_rh', 'clave_jde', 'foto', 'password1', 'password2', 'rfc', 'accept_terms' ] labels = { 'username': '******', 'first_name': 'Nombre', 'last_name': 'Apellidos', 'email': 'Email', } widgets = { 'username': HiddenInput(attrs={'class': 'form-control input-xs'}), 'first_name': HiddenInput(attrs={'class': 'form-control input-xs', 'readonly': 'True'}), 'last_name': HiddenInput(attrs={'class': 'form-control input-xs', 'readonly': 'True'}), 'email': TextInput(attrs={'class': 'form-control input-xs', 'required': 'required'}), } def __init__(self, *args, **kwargs): super(UserRegistroForm, self).__init__(*args, **kwargs) self.fields['username'].required = False self.fields['first_name'].required = False self.fields['last_name'].required = False self.fields['email'].required = True self.fields['rfc'].required = True self.fields[ 'clave_rh'].choices = EmpleadoBusiness.get_SinUsuario_ForSelect() self.fields['clave_jde'].required = False self.fields['foto'].required = False self.fields['fecha_nacimiento'].required = False self.fields['accept_terms'].required = True def clean(self): cleaned_data = super(UserRegistroForm, self).clean() clave_rh = cleaned_data.get("clave_rh") rfc = cleaned_data.get("rfc") password1 = cleaned_data.get("password1") password2 = cleaned_data.get("password2") email = cleaned_data.get("email") accept_terms = cleaned_data.get("accept_terms") if clave_rh and rfc and email and password1 and password2 and accept_terms: try: datos = EmpleadoBusiness.get_ByNumero(clave_rh) except Exception as error: raise ValidationError( str(error) ) if datos.pers_empleado_numero: ebs_rfc = datos.pers_rfc.replace("-", "") rfc = rfc.replace("-", "").upper() if ebs_rfc != rfc: raise ValidationError( 'No existe un usuario con el RFC proporcionado') username = datos.pers_empleado_numero first_name = "%s %s" % ( datos.pers_primer_nombre, datos.pers_segundo_nombre.replace("-", "")) last_name = "%s %s" % ( datos.pers_apellido_paterno, datos.pers_apellido_materno.replace("-", "")) self.cleaned_data["username"] = username self.cleaned_data["first_name"] = first_name self.cleaned_data["last_name"] = last_name fecha = parser.parse(datos.pers_fecha_nacimiento) self.cleaned_data["fecha_nacimiento"] = fecha.date() return self.cleaned_data else: raise ValidationError( "El empleado no tiene un numero especificado" )
class CustomerImportForm(Form): input_file = FileField(label=_("Import file"), required=False)
class ActiveDirectoryForm(ModelForm): ad_certfile = FileField(label=_("Certificate"), required=False) advanced_fields = [ 'ad_netbiosname', 'ad_use_keytab', 'ad_kerberos_keytab', 'ad_ssl', 'ad_certfile', 'ad_verbose_logging', 'ad_unix_extensions', 'ad_allow_trusted_doms', 'ad_use_default_domain', 'ad_dcname', 'ad_gcname', 'ad_kerberos_realm', 'ad_timeout', 'ad_dns_timeout', 'ad_idmap_backend' ] class Meta: fields = '__all__' exclude = ['ad_idmap_backend_type'] model = models.ActiveDirectory widgets = { 'ad_bindpw': forms.widgets.PasswordInput(render_value=False), } def __original_save(self): for name in ('ad_domainname', 'ad_netbiosname', 'ad_allow_trusted_doms', 'ad_use_default_domain', 'ad_use_keytab', 'ad_unix_extensions', 'ad_verbose_logging', 'ad_bindname', 'ad_bindpw'): setattr(self.instance, "_original_%s" % name, getattr(self.instance, name)) def __original_changed(self): if self.instance._original_ad_domainname != self.instance.ad_domainname: return True if self.instance._original_ad_netbiosname != self.instance.ad_netbiosname: return True if self.instance._original_ad_allow_trusted_doms != self.instance.ad_allow_trusted_doms: return True if self.instance._original_ad_use_default_domain != self.instance.ad_use_default_domain: return True if self.instance._original_ad_unix_extensions != self.instance.ad_unix_extensions: return True if self.instance._original_ad_verbose_logging != self.instance.ad_verbose_logging: return True if self.instance._original_ad_bindname != self.instance.ad_bindname: return True if self.instance._original_ad_bindpw != self.instance.ad_bindpw: return True if self.instance._original_ad_use_keytab != self.instance.ad_use_keytab: return True return False def __init__(self, *args, **kwargs): super(ActiveDirectoryForm, self).__init__(*args, **kwargs) if self.instance.ad_bindpw: self.fields['ad_bindpw'].required = False self.__original_save() self.fields["ad_enable"].widget.attrs["onChange"] = ( "activedirectory_mutex_toggle();") def clean_ad_certfile(self): filename = "/data/activedirectory_certfile" ad_certfile = self.cleaned_data.get("ad_certfile", None) if ad_certfile and ad_certfile != filename: if hasattr(ad_certfile, 'temporary_file_path'): shutil.move(ad_certfile.temporary_file_path(), filename) else: with open(filename, 'wb+') as f: for c in ad_certfile.chunks(): f.write(c) f.close() os.chmod(filename, 0400) self.instance.ad_certfile = filename return filename def clean(self): cdata = self.cleaned_data if not cdata.get("ad_bindpw"): cdata['ad_bindpw'] = self.instance.ad_bindpw if self.instance.ad_use_keytab is False: bindname = cdata.get("ad_bindname") bindpw = cdata.get("ad_bindpw") domain = cdata.get("ad_domainname") binddn = "%s@%s" % (bindname, domain) errors = [] ret = FreeNAS_ActiveDirectory.validate_credentials(domain, binddn=binddn, bindpw=bindpw, errors=errors) if ret is False: raise forms.ValidationError("%s." % errors[0]) return cdata def save(self): enable = self.cleaned_data.get("ad_enable") if self.__original_changed(): notifier()._clear_activedirectory_config() started = notifier().started("activedirectory") super(ActiveDirectoryForm, self).save() if enable: if started is True: started = notifier().restart("activedirectory") if started is False: started = notifier().start("activedirectory") if started is False: self.instance.ad_enable = False super(ActiveDirectoryForm, self).save() raise ServiceFailed("activedirectory", _("Active Directory failed to reload.")) else: if started == True: started = notifier().stop("activedirectory")
class CommissioningScriptForm(Form): """CommissioningScriptForm for the UI The CommissioningScriptForm accepts a commissioning script from the settings page in the UI. This form handles accepting the file upload and setting the script_type to commissioning if no script_script is set in the embedded YAML. The ScriptForm above validates the script itself. """ content = FileField(label="Commissioning script", allow_empty_file=False) def __init__(self, instance=None, *args, **kwargs): super().__init__(*args, **kwargs) self._form = None def clean_content(self): content = self.cleaned_data['content'] script_name = content.name script_content = content.read().decode() try: script = Script.objects.get(name=script_name) except Script.DoesNotExist: form = ScriptForm(data={'script': script_content}) # If the form isn't valid due to the name it may be because the # embedded YAML doesn't define a name. Try again defining it. if not form.is_valid() and 'name' in form.errors: form = ScriptForm(data={ 'name': script_name, 'script': script_content }) else: form = ScriptForm(data={'script': script_content}, instance=script) self._form = form return content def is_valid(self): valid = super().is_valid() # If content is empty self.clean_content isn't run. if self._form is not None and not self._form.is_valid(): # This form only has content so all errors must be on that field. if 'content' not in self.errors: self.errors['content'] = [] for key, errors in self._form.errors.items(): for error in errors: self.errors['content'].append('%s: %s' % (key, error)) return False else: return valid def save(self, request, *args, **kwargs): script = self._form.save(*args, **kwargs, commit=False, request=request, endpoint=ENDPOINT.UI) # If the embedded script data did not set a script type, # set it to commissioning. if 'script_type' not in self._form.data: script.script_type = SCRIPT_TYPE.COMMISSIONING script.save()
class ImageConverterForm(Form): """ A simple for that merely provides a FileField. """ file = FileField(label='', help_text='')