django 如何重定向匿名用户直到他得到正确的验证码

wbgh16ku  于 2023-03-09  发布在  Go
关注(0)|答案(1)|浏览(96)

我怎样才能强迫匿名用户停留在一个页面上,一直把他重定向到那个页面,直到他在那里得到正确的验证码?为了处理验证码表单,我可以使用django simple captcha,我的问题是如何知道验证码是否被解决,如果没有,我如何重定向他。
confirmation.html

{% extends 'base/base.html' %}
{% block content %}
<div class="content">
    <h2 class="title">Captcha test.</h2>
    <form method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form }}
        <div>
            <button type="submit">Update</button>
        </div>
    </form>
</div>
{% endblock %}

forms.py

from django import forms
from captcha.fields import CaptchaField

class ConfirmationForm(forms.Form):
    captcha = CaptchaField()
    class Meta():
        fields = ['captcha']

    def save(self):
        # some type of anonymous user confirmation variable that I could set to true to stop redirecting the user
        anonymous.human = True

urls.py

from django.urls import path
from home.views import Confirmation, Home

urlpatterns = [
    path('', Confirmation, name='confirmation'),
    path('', Home, name='home'),
]

views.py

def Confirmation(request):
    if request.method == 'POST':
        if anonymous.human == True:
            return redirect('home')
        if anonymous.human == False:
            return redirect('confirmation')
    else:
        form = ConfirmationForm()

    context = {
        'form': form,
    }

    return render(request, 'base/confirmation.html', context)


def Home(request):
    if human == False:
        return redirect('confirmation')

    context = {
        ...
    }

    return render(request, 'base/home.html', context)
wgxvkvu9

wgxvkvu91#

您可以通过验证以下形式来了解captcha是否正确:

def confirmation(request):
    if request.method == 'POST':
        form = ConfirmationForm(request.POST)
        
        if form.is_valid():
            request.session['is_human'] = True
            return redirect('/home/')
    else:
        form = ConfirmationForm()

    return render(request, 'base/confirmation.html', {'form': form})

def home(request):
    if request.session.get('is_human'):
        print('User is human')

    return render(request, 'base/home.html', {})

如果验证码不匹配,则视图将return render(request, 'base/confirmation.html', context)并呈现表单错误。

相关问题