【问题标题】:Call UpdateView without going to the UpdateView page in Django调用 UpdateView 而不去 Django 中的 UpdateView 页面
【发布时间】:2021-11-17 23:47:03
【问题描述】:

我正在寻找从 Django 中的模型对象创建可更新列表的最佳方法。

假设我有一个models.py:


class Machine(models.Model):
    machine = models.CharField(max_length=10, blank=True)
    currently_running = models.CharField(max_length=30, blank=True)

我有一个views.py,它显示了该模型中的对象:


class MachineView(ListView):
    model = Machine
    fields = ['machine', 'currently_running']
    template_name = 'viewer/machine_view.html'

class MachineUpdateView(UpdateView):
    model = Machine
    fields = ['currently_running']
    template_name = 'viewer/machine_update_view.html'

然后我有一个模板,machine_view.html:

...

<table>
  <tr>
    <th>Machine</th>
    <th>Part Running</th>
    <th></th>
  </tr>
  {% for machine in object_list %}
  <tr>
    <td>{{machine.machine}}</td>
    <td>{{machine.currently_running}}</td>
    <td> <a href="{% url 'machine_update_view' pk=machine.pk %}">Change</a> </td>
  </tr>
  {% endfor %}
</table>
...

和 machine_update_view.html:

...

<form method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Update">
</form>
...

目前这会将用户带到他们输入单个参数的更新页面,然后再次按更新。

是否可以通过自动传递的参数来做到这一点?

因此,他们无需前往更新页面,只需进行所需的更改,然后直接发送更新请求即可。然后刷新页面,这样他们就可以看到他们所做的更新。

这个可以吗?


编辑:为了清楚我想要做什么,我想添加以下行:

<td><input type="text" name="currently_running"></td>

到 machine_view.html。

或 DetailView 中类似的内容,将作为参数发送。

这样我可以完全绕过 UpdateView 页面。只需从 DetailView 调用它,它就会进行更新。

【问题讨论】:

  • 听起来像是 ajax 的工作 - 您是否考虑过将其作为您的解决方案?
  • 我还没有考虑过。我不确定从哪里开始,但我现在会开始研究它。感谢您的建议。

标签: django django-views django-class-based-views


【解决方案1】:

这是一个关于如何使用 javascript(jquery 和 ajax)动态更新网页的示例:

template.html

<!-- we will use js to send a post request when this button is clicked -->
<button id="my-button">Submit</button>

script.js


// using jquery, we will set the function that executes when the button is clicked
$('#my-button').click(function() {

  // launch an ajax request:
  $.ajax({
    type : 'POST',
    url : '<the-url>',
    data : {
      someKey : 'someValue'
    },
    success : function(response) {
      
      // this function executes when we receive a succesful response from the backend

      // unpack the response:
      result = response.result;

      // update html page:
      ...
 
   }
  }
});

views.py

def my_view_function(request):

    """ this function executes when the ajax request is sent """

    # unpack the request
    some_value = request.POST.get('someKey')

    # do some logic:
    ...
  
    # pack the response:
    response = {
        "result" : "some result"
    }

    return JsonResponse(response)

使用此模式,您可以创建动态页面,无需用户刷新即可自行更新。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-15
    • 2017-01-02
    • 1970-01-01
    • 2015-10-17
    • 2019-09-17
    • 1970-01-01
    • 1970-01-01
    • 2014-02-01
    相关资源
    最近更新 更多