我有一个带有ModelForm的表格,并有一个额外的字段(ImageField)。我试图在Forms.py
中验证此字段 def clean_icono(self):
icon = self.cleaned_data['icono']
if icon:
w, h = get_image_dimensions(icon)
if w != 127:
raise forms.ValidationError("El icono debe ser de 127 pixeles de ancho")
if h > 84:
raise forms.ValidationError("El icono debe ser de 84 pixeles de largo")
else:
raise forms.ValidationError("No se encuentra un icono")
return icon
在html中,我有一个ajax函数,该函数以模式显示错误
$('#bd_form').on('submit', function (e) {
e.preventDefault();
var data = new FormData($('form').get(0));
$.ajax({
type: $(this).attr('method'),
url: this.action,
data: data, // recupera los datos del formulario para usarlos en caso de error, no funciona con imagenes y archivos
cache: false,
processData: false,
contenType: false ,
success: function (data, status) {
$('#popup').find('#bd_form').off('submit', '#bd_form');
$("#bd_form").load(" #bd_form");
$('#popup').modal('hide');
$("#bd_table").load(" #bd_table");
},
error: function (request, type, errorThrown) {
var data = jQuery.parseJSON(request.responseText);
$('#popup').find('#bd_form').off('submit', '#bd_form');
$('#popup').find('#errores').empty();
for (var key in data) {
$('#popup').find('#errores').append(key + ': ' + data[key] + '<br>');
}
$('#popup').find('#form-error').show();
}
});
return false;
});
但是我总是收到“没有图标的错误”错误,我无法保存imagefield。我尝试使用serialize()发送数据,但是不起作用。我读到我必须使用FormData发送文件,但是不断收到错误
html文件的显示:
<form id="bd_form" action="{{ request.path }}" method="POST" name = "bd_form" role="form" enctype="multipart/form-data">
<!-- Modal body -->
{% csrf_token %}
<div class="modal-body">
<div class="container-fluid">
<div id="form-error" class="alert alert-danger" role="alert" style="display: none;">
<a href="#" class="close" onclick="$('#form-error').hide()" aria-label="close">×</a>
<p>Este formulario contiene los siguientes errores:</p>
<p id="errores"></p>
</div>
<div class="card">
<div id=form-body class="card-body row">
{% bootstrap_form_errors form type='fields'%}
{% for field in form %}
{% if forloop.counter == 4 %}
{% bootstrap_field field form_group_class='form-group col-6' %}
{% elif forloop.counter == 5 %}
{% bootstrap_field field form_group_class='form-group col-6' %}
{% elif forloop.last %}
<div class="form-group col-3">
<p> Icono actual</p>
{% comment %} rescata el icono segun la clave primaria {% endcomment %}
<img id = "icono" src="/static/media/db-icon-{{object.pk}}.png" alt="No hay icono" style="width: 127px; height: 84px;">
</div>
{% bootstrap_field field field_class='mt-4' form_group_class='form-group col-3 ' %}
{% else %}
{% bootstrap_field field form_group_class='form-group col-12' %}
{% endif %}
{% endfor %}
</div>
</div>
</div>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Enviar</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
</div>
</form>