Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีเพิ่ม Captcha ในเว็บไซต์ Django


Captcha เป็นวิธียืนยันตัวตนยุคใหม่ ใช้ในเว็บไซต์ทุก 1 ใน 2 เว็บ ใช้ Google Captcha ยุ่งยาก แต่ Django มีวิธีง่ายกว่า

บทความนี้สอนสร้าง Captcha ใน Django

ตัวอย่าง

สร้างโปรเจกต์และแอป

ติดตั้ง django-simple-captcha:

pip install django-simple-captcha

ใน settings.py เพิ่มแอปและ "captcha" ใน INSTALLED_APPS:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    "captchaproject",  # ชื่อแอป
    "captcha"  # โมดูล
]

ใน urls.py ของโปรเจกต์:

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"))
]

ใน forms.py ของแอป:

from django import forms
from captcha.fields import CaptchaField

class MyForm(forms.Form):
    captcha = CaptchaField()

รัน python manage.py migrate

ใน views.py:

from django.shortcuts import render
from .forms import MyForm

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

สร้าง HTML ใน templates:

<!DOCTYPE html> <html>
<head> <title>Tut</title> </head>
<body>
    <form method="POST" novalidate>
        {% csrf_token %}
        {{ form.captcha }}
        <input type="submit" value="submit">
    </form>
</body> </html>

เอาต์พุต

วิธีเพิ่ม Captcha ในเว็บไซต์ Django