【问题标题】:Can not call Django view function via/ using ajax function无法通过/使用 ajax 函数调用 Django 视图函数
【发布时间】:2021-10-24 09:46:25
【问题描述】:

views.py:

def post_upload(request, resolution, format, size):
    print(resolution)
    print(format)
    print(size)
    return render(request, 'upload .html')

urls.py:

path(r'^post_upload/$', views.post_upload, name='post_upload')

give.js:

$(".btn").bind('click', function(){

    console.log('download button clicked');

    var resolution = $(this).closest("tr").find(".resolution").text();
    var format = $(this).closest("tr").find(".format").text();
    var size = $(this).closest("tr").find(".size").text();
    var csrf_token = $("input[name='csrfmiddlewaretoken']").val();


    console.log(resolution,format,size, csrf_token);
    $.ajaxSetup({
        headers: {
        'X-CSRFToken': csrf_token
        }
    });
    $.ajax({
    type: 'POST',
     url : "{% url 'post_upload' %}",
     data: {
        resolution: resolution,
        format: format,
        size: size,
     },
     dataType:"html",
     success: function(data, status, xhr){
        //do something with your data
    }
    });

    return false;
});

html代码: 在这个按钮中动态创建。

<form>
{% csrf_token %}
<button type="button"  name="url" value="{{ request.GET.url }}"  type="submit" id="download" class="btn btn-success" >Download</button>
</form>

 <script src="https://code.jquery.com/jquery-3.6.0.js"></script>

    <script src="{% static 'js/popper.min.js' %}"></script>
    <script src="{% static 'js/bootstrap.bundle.min.js'%} "></script>

    <script src="{% static 'js/plugin.js' %}"></script>
    <!-- sidebar -->
    <script src="{% static 'js/jquery.mCustomScrollbar.concat.min.js' %}"></script>
    <script src="{% static 'js/custom.js' %}"></script>
    <script src="https:cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.min.js"></script>
    <script src="{% static 'js/give.js' %}"></script>

我可以尝试使用或通过保存为 give.js 的 ajax 函数在 views.py 中调用 post_upload() 函数。但是在这样的错误中未找到:/{% url 'post_update' }

和 404

【问题讨论】:

  • 不要只显示你的代码。说明您正在尝试做什么以及发生了什么?
  • 我无法使用 ajax 调用我的 django 函数
  • 这可能意味着任何事情。具体一点。
  • 我可以尝试调用 post_upload() 视图函数,使用 ajax
  • 没有。你不能,因为你的脚本是外部的,django 模板语法可以工作。

标签: jquery django ajax


【解决方案1】:

路径没有意义,因为path(…) [Django-doc] 使用路径语法,不是正则表达式。此外,您不能在 .js 文件中使用 {% url … %} [Django-doc],因为 JavaScript 文件只是简单地返回,它不会被渲染。

因此,这意味着您将路径重写为:

urlpatterns = [
    # …,
    path('post_upload/', views.post_upload, name='post_upload')
    # …
]

give.js 文件中,我们使用:

$.ajax({
    type: 'POST',
    url : '/post_upload/',
    # …
});

【讨论】:

    猜你喜欢
    • 2020-08-31
    • 1970-01-01
    • 2019-03-11
    • 2021-02-13
    • 2020-12-22
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2015-03-06
    相关资源
    最近更新 更多