【问题标题】:Django view bypass render requestDjango视图绕过渲染请求
【发布时间】:2021-09-13 00:59:16
【问题描述】:

我有一个包含数据的表格和一个按钮,用户可以在其中删除整个对象,我实现了一个模板,用户应该在该模板中被重定向,以便他可以选择确认删除或取消删除。

但是当我单击删除按钮时,它会立即删除对象,知道如何告诉视图首先转到该模板,然后,如果是这种情况,删除对象?

这里是模板borrar_oficio.html我想在点击删除按钮后被重定向:

{% extends 'base.html' %}

{% block content %}

<p>Are you sure you want to delete {{ item }}?</p>

<form action="{% url 'oficios:borrar' item.id %}" method="POST">
    {% csrf_token %}

    <a href="{% url 'oficios:list' %}">Cancelar</a>

    <input type="submit" name="Confirmar">
</form>

{% endblock content %}

这是 模板 中按钮所在的部分:

 <form action="{% url 'oficios:borrar' oficio.folio  %}" method='POST'>
 {% csrf_token %}
 <button type="submit" class="btn btn-danger btn-lg" data-toggle="tooltip" data-placement="top" title="Eliminar"><i class="fas fa-trash-alt"></i></button>
 </form>  

这里是删除views.py中对象的方法

@login_required(login_url="/accounts/login/")
def borrar_oficio(request, pk):
    oficio = Oficio.objects.get(folio=pk)
    if request.method == "POST":
        oficio.delete()
        return redirect('oficios:list')
    context = {'item': oficio}
    return render(request, "borrar_oficio.html", context)

还有我的那个应用的urls.py

app_name = 'oficios'

urlpatterns = [
    path('', views.lista_oficios, name="list"),
    path('crear/', views.crear_oficio, name="crear"),
    path('editar_oficio/<str:pk>', views.editar_oficio, name="editar"),
    path('borrar_oficio/<str:pk>', views.borrar_oficio, name="borrar"),
    path('dependencia/', views.agregar_dependencia, name="dependencia"),
]

【问题讨论】:

    标签: django django-rest-framework django-views django-templates


    【解决方案1】:

    表单上的按钮向视图发送POST 请求,该请求有效,因此它会执行删除操作,然后重定向用户。如果同一视图被 GET 请求击中,则您呈现 borrar_oficio.html 模板,但这不是从垃圾桶按钮发生的。

    如果您想从用户那里得到他们想要提交删除请求的确认,那么您可以使用表单上的 javascript 来完成。像这样的东西会出现一个确认对话框;

    <form action="{% url 'oficios:borrar' oficio.folio  %}" method="POST" onsubmit="return confirm('Do you really want to delete the object?');">
      {% csrf_token %}
      <button type="submit" class="btn btn-danger btn-lg" data-toggle="tooltip" data-placement="top" title="Eliminar">
        <i class="fas fa-trash-alt"></i>.
      </button>
    </form>  
    

    【讨论】:

    • 是的,我也想过这个解决方案,但是在button 上使用onclick="return confirm('¿Are you sure you want to delete it?')",你建议我改用JS 吗?就像你的回答一样。谢谢
    • 使用onsubmit 应该会更好地解决这个问题
    猜你喜欢
    • 2020-04-02
    • 1970-01-01
    • 2014-09-18
    • 2017-04-22
    • 2018-12-13
    • 1970-01-01
    • 2017-06-23
    • 2015-02-04
    • 1970-01-01
    相关资源
    最近更新 更多