python-3.x 我无法将表单附加到列表

k10s72fa  于 2023-06-07  发布在  Python
关注(0)|答案(1)|浏览(147)

为什么这段代码不会将任务追加到任务我一直在学习CS50课程,在我应用这段代码后,我没有看到预期的结果,我尝试了所有方法,但仍然表单不会追加到任务列表

from django.shortcuts import render
from django import forms
from django.http import HttpResponseRedirect
from django.urls import reverse

class NewTaskForm(forms.Form):
    task = forms.CharField(label="Task Text")
    
tasks = ['finish', 'study', 'reset']

# Create your views here.
def index(request):
    
    return render(request, "task/index.html",{
        "tasks":tasks
    })
    
def add(request):
    if request.method =="post":
        form = NewTaskForm(request.post)
        if form.is_valid():
            task = form.cleaned_data["task"]
            tasks.append(task)
            return HttpResponseRedirect(reverse("task:index"))
        else:
            return render(request, "task/add.html", {
                "form":form
            })
    return render(request, "task/add.html",{
        "form":NewTaskForm()
    })
mnemlml8

mnemlml81#

有一些问题,方法总是大写,数据存储在request.POST中:

from django.shortcuts import redirect

def add(request):
    if request.method == 'POST':
        form = NewTaskForm(request.POST, request.FILES)
        if form.is_valid():
            task = form.cleaned_data["task"]
            tasks.append(task)
            return redirect('task:index')
    else:
        form = NewTaskForm()
    return render(request, 'task/add.html', {'form': form})

也就是说,将数据存储在(全局)变量中是一个非常糟糕的主意。它引入了全局状态,这是一个严重的反模式。

相关问题