图片验证码
图片验证码
Captcha is one of the modern ways used for verification in websites;
it is very cool way and every second website is using it. You can use
Google captcha but it is really a headache to apply it; however in
Django, we have a simpler method to do so.
In this article, we are going to learn how to create a captcha in a Django website. So, let's get started.
Example
First of all, create a Django project and an app.
Now install the django-simple-captcha library −
pip install django-simple-captcha
Go to settings.py and inside INSTALLED_APPS, add your app and "captcha": −
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
"captchaproject", #My app name
"captcha" # the module name
]
It will add captcha as an app.
In project's root directory, add the following lines −
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("captchaproject.urls")),
path('/captcha',include("captcha.urls"))
]
It will add url for my app and the captcha url where verification will occur.
In app's main directory, create a forms.py and type −
from django import forms
from captcha.fields import CaptchaField
class MyForm(forms.Form):
captcha=CaptchaField()
Here we created a form with captcha field.
Don't forget to run "python manage.py migrate"
Now in app's view.py, add the following lines −
from django.shortcuts import render
from .forms import MyForm
Create your views here.
def home(request):
if request.method=="POST":
form=MyForm(request.POST)
if form.is_valid():
print("success")
else:
print("fail")
form=MyForm()
return render(request,"home.html",{"form":form})
We render the form in home view and in POST handler, we verify the
form or we can say captcha and after verification, we print the result.
Create an HTML file in the templates directory (directory where you add every HTML or CSS file that you
render, I assume you know and already configure it) and add the
following lines −
This is the frontend where we are rendering the captcha form.
We are done; now you can proceed to check the output.
Output
按照上述步骤,注意captcha URL路由按照上述指示在settings.py配置
然后无需做其他,在views方法中
def account_login(request):
# if request.method == 'GET':
# return render(request,'account_login.html')
# username = request.POST.get('username')
# password = encrypt(request.POST.get('password'))
# print(password)
# admin_object = models.Admin.objects.filter(username=username, password=password).first()
# if not admin_object:
# return render(request,'account_login.html')
# request.session['info'] = {'id':admin_object.id,'username':admin_object.username}
# return redirect('/admin/list/')
if request.method == 'GET':
form = LoginForm()
print(form)
return render(request,'account_login.html',{'form':form})
form = LoginForm(data=request.POST)
if form.is_valid():
admin_object = models.Admin.objects.filter(username=form.cleaned_data.get('username'),password=form.cleaned_data.get('password') ).first()
if not admin_object:
form.add_error('password','用户名或者密码错误')
return render(request,'account_login.html',{'form':form})
else:
request.session['info'] = {'id':admin_object.id,'username':admin_object.username}
return redirect('/admin/list/')
return render(request,'account_login.html',{'form':form})