使用django-simple-captcha 在html中使用{{form}}渲染后 图形验证码看不到

Forms.py

class LoginForm(BootStrapForm, forms.ModelForm):
    username = forms.CharField(label='用户名', max_length=100, widget=forms.TextInput(attrs={'placeholder': '请输入用户名'}))
    password = forms.CharField(
        label="密码",
        max_length=64,
        widget=forms.PasswordInput(attrs={'placeholder': '请输入密码'})
    )
    email = forms.EmailField(label='邮箱', required=False, widget=forms.EmailInput(attrs={'placeholder': '请输入邮箱'}))
    captcha = CaptchaField(
        label="图形验证码",
        widget=forms.TextInput(attrs={'placeholder': '请输入验证码'})
    )

    class Meta:
        model = User
        fields = ['username']

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_password(self):
        row_obj = User.objects.filter(username=self.cleaned_data.get('username')).first()
        if row_obj and row_obj.password == md5_encrypt(self.cleaned_data['password']):
            return self.cleaned_data['password']
        else:
            raise forms.ValidationError("用户名或密码错误")

    def clean_verification_code(self):
        code_in_session = self.request.session.get('login_verification_code')
        if not code_in_session:
            raise forms.ValidationError("验证码已过期")
        if not self.cleaned_data['verification_code'] == code_in_session:
            raise forms.ValidationError("验证码错误")
        return self.cleaned_data['verification_code']

    def clean_captcha(self):
        if not self.cleaned_data['captcha'] == self.request.session.get('captcha_key'):
            raise forms.ValidationError("验证码错误")
        return self.cleaned_data['captcha']

Views.py

def login(request):
    if request.method == 'GET':
        form = LoginForm(request=request)
        # 生成验证码信息
        captcha_info = {'image_url': '/captcha/', 'hashkey': 'your_captcha_key'}
        context = {
            'form': form,
            'captcha_image_url': captcha_info['image_url'],
            'hashkey': captcha_info['hashkey'],
            'nid': 2
        }
        return render(request, 'UserAuth/UserAuth.html', context=context)

    # if method is POST
    form = LoginForm(data=request.POST, request=request)
    if not form.is_valid():
        # 如果表单验证失败,重新生成验证码信息
        captcha_info = {'image_url': '/captcha/', 'hashkey': 'your_captcha_key'}
        context = {
            'form': form,
            'captcha_image_url': captcha_info['image_url'],
            'hashkey': captcha_info['hashkey'],
            'nid': 2
        }
        return render(request, 'UserAuth/UserAuth.html', context=context)
    username = form.cleaned_data['username']
    password = form.cleaned_data['password']
    user = authenticate(request, username=username, password=password)
    if user is not None:
        request.session.set_expiry(60 * 60 * 24 * 7)  # 7天免登录
        return redirect(reverse('Forum:home'))
    else:
        context = {
            'form': form,
            'error_message': "用户名或密码错误",
            'nid': 2
        }
        return render(request, 'UserAuth/UserAuth.html', context=context)

UserAuth.html

<form method="post" novalidate>
        {% csrf_token %}

        {{form}}

        {% if nid == 1 %}
            <input type="submit" value="注 册" class="btn btn-primary">
        {% else %}
            <input type="submit" value="登 录" class="btn btn-primary">
        {% endif %}
        <a href="/">取 消</a>

        {% if nid == 1 %}
            &lt;div style="text-align: right;"&gt;
                已有账号?<a href="/auth/login/">去登录!</a>
            &lt;/div&gt;
        {% else %}
            &lt;div style="text-align: right;"&gt;
                还没有账号?<a href="/auth/register/">去注册一个!</a>
            &lt;/div&gt;
        {% endif %}
    &lt;/form&gt;

界面:

评论 0