我想使用ajax将图像文件和其他一些数据上传到Django数据库。每次我使用formData进行此操作时,调试时总是返回空。另外我的序列化器没有验证。请帮助我解决此问题。还有其他方法可以将图像文件发送到服务器。
function add_bike_model(btn){
debugger;
var data=new FormData()
data.append('image',$("#bike_model_name")[0].files[0])
// BikeModels = document.getElementById('bike_model_name').value;
// var e = document.getElementById("city_drop");
// var strUser = e.options[e.selectedIndex].value;
// image = document.getElementById('img_file').value;
// e.preventDefault();
// var data = new FormData($('#form').closest('form')[0]);
console.log('hello')
data = {"CityForCars":strUser, "BikeModels": BikeModels, 'Image':image}
$.ajax({
type: 'POST',
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
url: baseUrl + "/bike_model/",
data:new FormData($("#moment-pane-upload-form")[0]),
success: function(data) {
console.log('sucessfully done')
console.log(data)
window.location.href = baseUrl + "/bike_model/";
}
});
}
<form name="add_model_form" id="add_model_form" enctype="multipart/form-data" class="comon-form" method="post">
<h3>ADD BIKE MODELS</h3>
<div class="col-md-6">
<div class="avatar-upload">
<div class="avatar-preview">
<div id="imagePreview" style="background-image: url(/static/Chatbot_Dashboard/img/logo/logo.png);"></div>
<img id="bike_image" src="">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group-inner">
<label>Bike Model Name <em>*</em></label>
<input class="form-control" placeholder="" type="name" id="bike_model_name" required="">
</div>
</div>
<div class="col-md-6">
<div class="form-group-inner">
<label>City <em>*</em></label>
<select style="width: 100%; background: #fff; padding: 7px;" id="city_drop">
<option value="" selected="selected">Select City</option>
{% for city in city.car_city %}
<option value="{{city.id}}">{{city.CityForCars}}</option>
{% endfor %}
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group-inner">
<label>Bike Image <em>*</em></label>
<input class="form-control" placeholder="" type="file" id="img_file" required="">
</div>
</div>
<div class="clearfix"></div>
<div class="mt20 text-center">
<button type="button" class="btn btn-primary" onclick="add_bike_model(this);" style="margin-right:10px;">Add</button><a href="/bike_model/"><input type="button" class="btn btn-primary" value="Cancel"></a>
</div>
<div class="clearfix"></div>
</form>
我的python代码是-
if request.method == 'POST':
import pdb;
pdb.set_trace()
print('a')
# input_data = json.loads(request.read().decode('utf-8'))
# print(input_data)
serializer = serializers.BikeModelSerializer(request.FILES, request.POST)
if serializer.is_valid():
serializer.save()
return render(request, "bike_model_add.html", {'car_city': car_city}, status=200)
return HttpResponse('error', status=400)