【问题标题】:Django How to pass a checkbox value into a functionDjango如何将复选框值传递给函数
【发布时间】:2021-02-05 16:36:07
【问题描述】:

我在 django 中创建了一个表,每行都有一个 id 和一个复选框。我为每个复选框分配了value 作为行的ID。当用户点击复选框时,我希望它调用一个函数并传入id 数字以及该复选框现在是否被选中。

sets.html:

 <td class="text-center">
     {% if set.status %}
        <input type="checkbox" checked name="inputs" value="{{ set.id }}" onclick="location.href='{% url 'dashboard:setUpdate' %}'">
     {% else %}
        <input type="checkbox" name="inputs" value="{{ set.id }}" onclick="location.href='{% url 'dashboard:setUpdate' %}'">
     {% endif %}
 </td>

views.py

def set_update(request):
    print(request.GET.getlist('inputs'))
    return redirect('dashboard:sets')

【问题讨论】:

    标签: python django


    【解决方案1】:

    为什么不用ajax?:

    模板.html:

    <head>
      ...
      <!-- import jquery/ajax -->
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    </head>
    <body>
      ...
      <!-- create a variable for the csrf token, then load the script.js file -->
      <script> var csrf_token = '{{csrf_token}}' </script> 
      <script src="{% static 'path/to/script.js' %}"></script>
    </body>
    

    script.js:

    function set_update() {
      
      // submit a request to the backend using ajax:
      $.ajax({
        url : 'the_url',
        type : 'POST',
        data : {
          csrfmiddlewaretoken : csrf_token, // from template.html
          id : $(this).val(),
        },
        success: function(response) set_update_success, // reference to function below:
      });
    
    }
    
    // executed on succesfully receiving a response from the backend:
    function set_update_success(response) {
    
      // unpack response from views.py (below):
      var data = response.data; 
      ...
    
      // redirect user:
      windlow.location('the_redirect_url');
    }
    
    // get all checkboxes and set the click function to 'set_update'
    // the identifier can be a class ('.class'), id ('#id'), etc.
    $('checkbox-identifier').click(set_update); 
    

    views.py:

    def set_update(request):
    
        # unpack post request:
        the_id = request.POST['id']
        ...
    
        # execute any logic as needed:
        ...
    
        # pack response:
        respone = json.dumps({
            'data' : 'some_data',
            ...
        })
    
        return HttpResponse(response)
    

    【讨论】:

    • 你好@Daniel,我以前从未使用过 Ajax。此外,我使用作为 SQL 查询的一部分返回的两个值,我只知道如何通过 python 来完成。
    • 没问题,我已经详细说明了我的答案。如果你学习了这个模式,你可以用 django 做很多事情。如果还有什么不清楚的,请告诉我。
    • 非常感谢。它按预期工作,但是我在控制台中遇到以下问题:Uncaught TypeError: t.nodeName is undefined 这显然与 $(this).val()
    猜你喜欢
    • 2020-12-20
    • 1970-01-01
    • 2015-06-07
    • 1970-01-01
    • 2014-12-29
    • 2020-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多