Django CSRF token在表单提交中丢失,尽管包含它

yvgpqqbh  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(125)

我正在做一个Django项目,我有一个表单来使用Twilio的API验证电话号码。但是,我遇到了一个问题,表单提交中缺少CSRF令牌,导致“CSRF令牌缺失”错误。
我已经在HTML模板的元素中包含了{% csrf_token %}模板标记。我还验证了在我的Django设置中启用了django.middleware.csrf.CsrfViewMiddleware中间件。

@login_required
def verify_phone_number(request):
    if request.method == 'POST':
        # Code to initiate phone number verification using Twilio's API
        
        # Code to Return an HTTP response with the HTML content when verification request wasnt sent
        html_content = """
        return HttpResponse(html_content)
    else:
        # Return an HTTP response with the HTML content
        html_content = """
        <!DOCTYPE html>
        <html>
        <head>
            <title>Verify Phone Number</title>
        </head>
        <body>
            <h1>Verify Your Phone Number</h1>

            <form method="post">
                {% csrf_token %}
                <label for="phone_number">Phone Number:</label>
                <input type="text" id="phone_number" name="phone_number" required>
                <button type="submit">Verify</button>
            </form>
        </body>
        </html>
        """
        return HttpResponse(html_content)
afdcj2ne

afdcj2ne1#

你需要渲染一个模板来使用{% csrf_token %}。这样做的话,实际的字符串{% csrf_token %}将在HTML文件中,而不是在Token字段中。
您需要将HTML放入模板文件中,然后为模板返回TemplateResponse
templates/verify.html:

<!DOCTYPE html>
        <html>
        <head>
            <title>Verify Phone Number</title>
        </head>
        <body>
            <h1>Verify Your Phone Number</h1>

            <form method="post">
                {% csrf_token %}
                <label for="phone_number">Phone Number:</label>
                <input type="text" id="phone_number" name="phone_number" required>
                <button type="submit">Verify</button>
            </form>
        </body>
        </html>

然后像这样修改代码:

@login_required
def verify_phone_number(request):
    if request.method == 'POST':
        # Code to initiate phone number verification using Twilio's API
        
        # Code to Return an HTTP response with the HTML content when verification request wasnt sent
        return HttpResponse('')
    else:
        # Return an Template response with the HTML content
        return TemplateResponse(request, 'verify.html', {})

相关问题