login with captcha

This commit is contained in:
wcharles 2019-10-09 14:21:19 +08:00
parent 98003e547b
commit 865579f8d2
6 changed files with 50 additions and 5 deletions

View File

@ -1,6 +1,7 @@
from django import forms
from captcha.fields import CaptchaField
class GroupsForm(forms.Form):
username = forms.CharField(label="用户名", max_length=128, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': "Username",'autofocus': ''}))
password = forms.CharField(label="密码", max_length=256, widget=forms.PasswordInput(attrs={'class': 'form-control','placeholder': "Password"}))
captcha = CaptchaField(label='验证码', error_messages={"invalid":"验证码错误"})

View File

@ -15,8 +15,10 @@
<div class="container">
<div class="col">
<form class="form-login" action="/groups/login/" method="post">
{% if message %}
<div class="alert alert-warning">{{ message }}</div>
{% if groups_form.captcha.errors %}
<div class="alert alert-warning">{{ groups_form.captcha.error_messages }}</div>
{% elif message %}
<div class="alert alert-warning">{{ message }}</div>
{% endif %}
{% csrf_token %}
<h3 class="text-center">欢迎登录</h3>
@ -28,6 +30,10 @@
{{ groups_form.password.label_tag }}
{{ groups_form.password }}
</div>
<div class="form-group">
{{ groups_form.captcha.label_tag }}
{{ groups_form.captcha }}
</div>
<div>
<button type="submit" class="btn btn-primary float-right">登录</button>
</div>
@ -43,3 +49,12 @@
</body>
</html>
<script>
$('.captcha').click(function () {
$.getJSON("/groups/refresh_captcha/", function (result) {
$('.captcha').attr('src', result['image_url']);
$('#id_captcha_0').val(result['key'])
});
});
</script>

View File

@ -1,4 +1,5 @@
from django.urls import path
from django.urls import include
from . import views
urlpatterns = [
@ -6,5 +7,6 @@ urlpatterns = [
path('index/', views.index, name='index'),
path('login/', views.login, name='login'),
path('logout/', views.logout, name='logout'),
path('captcha/', include('captcha.urls')),
path('refresh_captcha/', views.refresh_captcha),
]

View File

@ -45,3 +45,14 @@ def logout(request):
return redirect('/groups/login')
request.session.flush()
return redirect('/groups/login')
import json
from captcha.models import CaptchaStore
from captcha.helpers import captcha_image_url
def refresh_captcha(request):
hashkey = CaptchaStore.generate_key()
image_url = captcha_image_url(hashkey)
return HttpResponse(json.dumps({'key': hashkey, 'image_url': image_url}), content_type='application/json')

View File

@ -39,6 +39,7 @@ INSTALLED_APPS = [
'django.contrib.staticfiles',
'safesite',
'groups',
'captcha',
]
MIDDLEWARE = [

View File

@ -0,0 +1,15 @@
# Generated by Django 2.1.4 on 2019-10-09 09:52
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('safesite', '0265_auto_20190917_1716'),
('safesite', '0267_auto_20190917_1543'),
('safesite', '0265_companyinfo'),
]
operations = [
]