当我添加 else 条件时,我的 for 循环停止工作

My for loop stops working when I add an else condition

我正在尝试定义一个函数以便在 wiki 应用程序中创建一个新页面。用户应提供标题和内容。如果标题已经存在于列表中,用户应该得到一条错误消息。如果不是,则新条目及其内容应保存在列表中。

到目前为止,这是我的代码:

def new_page(request):
    if request.method == "POST":
        title = request.POST.get("title")
        entries = util.list_entries() #this function is already defined and it returns a list of all names of encyclopedia entries.

        for entry in entries:
            if title.lower() == entry.lower():
                return HttpResponse(f"ERROR: {entry} Already Exists")
    else:
        return render(request,"encyclopedia/new_page.html")

上面的代码工作正常,当我输入现有标题时,我收到错误消息。

当我添加一个 else 条件时,问题就开始了。这是一个示例(只是为了尝试代码,我还不想保存内容。)

def new_page(request):
    if request.method == "POST":
        title = request.POST.get("title")
        entries = util.list_entries()

        for entry in entries:
            if title.lower() == entry.lower():
                return HttpResponse(f"ERROR: {entry} Already Exists")
            else:
                return HttpResponse("Thank you for your contribution!")
    else:
        return render(request,"encyclopedia/new_page.html")

现在,即使我输入现有标题,我也会收到“感谢您的贡献!”。我不知道是什么导致了这个问题。你能帮忙吗?

new_page.html:

{% extends "encyclopedia/layout.html" %}

{% block title %}
    Create New Page
{% endblock %}

{% block body %}
    <h1>Create Your Entry</h1>
    <form action="{% url 'new_page' %}" method="POST">
        {% csrf_token %}
        <input type="text" name="title" placeholder="Title" style="width: 200px; text-align: center;">
        <textarea name="new_entry" id="new_entry" cols="30" rows="10"></textarea>
        <input type="submit" name="save_entry" id="save_entry" value="Save">
    </form>
{% endblock %}

由于 for 循环中 else 中的 return 语句,函数退出。

你应该把页面是否已经存在保存在一个变量中,如下所示:

def new_page(request):
    if request.method == "POST":
        title = request.POST.get("title")
        entries = util.list_entries()
        pageExists=False
        for entry in entries:
            if title.lower() == entry.lower():
                pageExists=True
        if pageExists:
            return return HttpResponse(f"ERROR: {entry} Already Exists")
        else:
            return HttpResponse(f"ERROR: {entry} Already Exists")
    else:
        return render(request,"encyclopedia/new_page.html")

return 导致函数在未命中的循环的第一次迭代中退出。您必须像这样将 return 语句向上移动两层:

def new_page(request):
    if request.method == "POST":
        title = request.POST.get("title")
        entries = util.list_entries()

        for entry in entries:
            if title.lower() == entry.lower():
                return HttpResponse(f"ERROR: {entry} Already Exists")
        # the loop is finished and did not find an existing entry, return success
        return HttpResponse("Thank you for your contribution!")
    else:
        return render(request,"encyclopedia/new_page.html")