图片验证码

图片验证码

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 −

          Tut              
         {%csrf_token%}          {{form.captcha}}                
   

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})

posted @   Jason_huawen  阅读(77)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
历史上的今天:
2022-05-30 利用Python实现完整的网站登录过程涵盖下载默认页面、自动提取表单的字段并将其提交完成登录过程
2022-05-30 利用Python实现目录遍历漏洞的发现工具
点击右上角即可分享
微信分享提示