django如何在html中仅使用{%url'x%}发出post请求

zbdgwd5y  于 2021-09-08  发布在  Java
关注(0)|答案(2)|浏览(228)

这是我的观点。

from django.shortcuts import render, redirect
from .models import Todo
from .forms import TodoForm
from django.views.decorators.http import require_http_methods

def index(request):
    return render(request, 'home.html')

def todoPanel(request):
    form = TodoForm()

    todo_list = Todo.objects.order_by('id')

    context =  {'form': form, 'tasks': todo_list}

    return render(request, 'todo_panel.html', context)

@require_http_methods
def addTask(request):
    form = TodoForm(request.POST)

    if form.is_valid():
        task = Todo(task=form.cleaned_data['task'])
        task.save()

    return redirect('panel')

这是我的URL.py

from django.urls import path
from . import views 
urlpatterns = [
    path('', views.index, name='home'),
    path('panel/', views.todoPanel, name='panel'),
    path('addTask', views.addTask, name='addTask')
    #path('delete_confirm', views.todo_delete, name='delete_confirm')
]

这是我的todo_panel.html

{% extends 'base.html' %}

{% block content %}
<h1>Todo Panel</h1>

<!-- Render the form here-->
<form action="{% url 'addTask' %}" method="POST">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Add">
</form>    

<!-- Display the todos here -->

<ul class="list-group">
{% for task in tasks %}
    <li class="list-group-item">{{ task }}</li>
{% endfor %}
</ul>
{% endblock content %}

我不想django将我重定向到addtask。。。我想让它发出一个发帖请求。我在这里读了这个例子https://github.com/prettyprinted/django_todo_app 他能够做到这一点,而无需重定向到添加。我只想让它发出post请求,这样它就可以将todo发布到数据库中。

ztmd8pv5

ztmd8pv51#

您已经在get请求中获取了表单,并添加了一个条件来处理post请求,如下所示

@require_http_methods
def addTask(request):
    if request.method == 'POST':
       form = ContactForm(request.POST)
       if form.is_valid():
          return redirect('panel')
    else:
       form = ContactForm()
    return render(request,"todo_panel.html",{'form':form})
1hdlvixo

1hdlvixo2#

尝试编辑 addTask 方法如下:

@require_http_methods
def todoPanel(request):
    if request.method == 'POST':
        form = TodoForm(request.POST)

        if form.is_valid():
            task = Todo(task=form.cleaned_data['task'])
            task.save()

        return redirect('panel')

    form = TodoForm()
    todo_list = Todo.objects.order_by('id')
    context =  {'form': form, 'tasks': todo_list}
    return render(request, 'todo_panel.html', context)

这将确保函数操作仅在请求为 POST .

相关问题