Jquery Django Ajax表单在“提交”之后重新加载;“成功”;
从我上一篇包含django和ajax()问题的文章扩展到以下情况,正如编辑中提到的: 我的jquery/ajax调用:Jquery Django Ajax表单在“提交”之后重新加载;“成功”;,jquery,django,ajax,image,upload,Jquery,Django,Ajax,Image,Upload,从我上一篇包含django和ajax()问题的文章扩展到以下情况,正如编辑中提到的: 我的jquery/ajax调用: <script> $(document).ready(function () { // This jquery changes the appearance of the django { form_image } var imgElement = $('#id_image'); imgElement.css('visi
<script>
$(document).ready(function () {
// This jquery changes the appearance of the django { form_image }
var imgElement = $('#id_image');
imgElement.css('visibility', 'hidden');
console.log($('#id_image').attr('type'))
// This function triggers the hidden submit,
// which triggers the ajax image request
imgElement.on({
change: function () {
$('#hidden-submit-img').click();
},
});
});
// This jquery is for the ajax post of the image
// Doing it with submit, the image wont get saved, but the request is "success"
// $('#image_form').submit(function (event) {
// Doing it with change, the image gets saved successfully, but the respond loads a new page
$('#image_form').change(function (event) {
event.preventDefault();
$.ajax({
data: {
image: $('#id_image').val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
},
enctype: $(this).attr('enctype'),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function () {
console.log(1);
},
error: function () {
console.log(0);
}
});
});
</script>
models.py:
class ImagesUpload(models.Model):
image = models.ImageField(upload_to=renaming_file)
def __str__(self):
return str(self.image)
home.html:
<form id="image_form" method="post" enctype="multipart/form-data" action="{% url 'website:image-feedback' %}">{% csrf_token %}
<button class="btn btn-secondary" onclick="$('#id_image').click()">Import Image</button>
{{ form_image.image }}
<input id="hidden-submit-img" value="SUBMIT" type="submit" style="visibility:hidden">
</form>
{%csrf\u令牌%}
导入图像
{{form_image.image}
我想我已经接近解决方案了,但也许我的技能还不够
我想上传一张图片,将其存储在我的数据库中,让我的网站继续运行,而无需重新加载/刷新。您的html表单
<form id="image_form"> #does not provide any attribute
{% csrf_token %}
{{ form_image.image }}
</form>
我给了你很多东西,你可以在你的代码中看到和应用,然后打开firefox浏览器,查看inspect element return you status code的网络选项卡,查看返回的状态代码,并告诉我是否有任何错误试着在你的视图中返回JsonResponse而不是HttpResponse这样做,我收到两个错误,缺少
method='POST'
和enctype='multipart/form data'
,并且this.files未定义
错误。添加缺少的属性无法解决问题我更新我的答案您需要在脚本应用中更改$(“#id_image”)。更改
这项工作是否检查itI更新答案,您需要在javascript表单数据中更改csrf令牌id,我在这里给您看$('input[name=csrfmiddlewaretoken]')。val()
让我知道您在应用csrf后出现了什么错误。在ajax成功后,您需要在这里处理验证。请在ajax的成功函数中请求清除图像输入字段$(this).val(“”)代码>并在列表中处理一个文件选择例外另一个方式您可以正确上传图片,这样您可以接受正确答案吗
<form id="image_form"> #does not provide any attribute
{% csrf_token %}
{{ form_image.image }}
</form>
<script>
$("#id_image").change(function(){ // here my second change apply id of image field
var formdata = new FormData(); //create formdata object
formdata.append('image',this.files[0])
formdata.append('csrfmiddlewaretoken',$('input[name=csrfmiddlewaretoken]').val()); //apply csrf token
$.ajax({
url:"{% url 'website:image-feedback' %}",
method:'POST',
data:formdata,
enctype: 'application/x-www-form-urlencoded',
processData:false,
contentType:false,
success:function(data){
//update src attribute of img tag
$('#profile_pic').attr('src',data.url);
$('#image_form').trigger('reset'); // This reloads the form for additional upload
},
error:function(error){
//display error base on return the view
alert(error.error)
}
});
return false;
});
</script>
def image_feedback(request): # url 'website:image-feedback'
if request.method == 'POST':
image = request.FILES.get('image')
img = ImagesUpload.objects.create(
image = image,
)
return JsonResponse(status=200,data={"url": img.url}) #return json response
else:
return JsonResponse(status=203,data={"error": "unauthorized request.!!"})