Django Simple Captcha 模块安装与使用指南
# 安装Django Simple Captcha模块
# 打开终端或命令行,输入以下命令:
pip install django-simple-captcha
# 在Django项目的settings.py中添加captcha应用
INSTALLED_APPS = [
...
'captcha',
...
]
# 运行数据库迁移命令
# 终端或命令行中,输入以下命令:
python manage.py migrate captcha
# 在urls.py中添加captcha的URL
from django.urls import path, include
urlpatterns = [
...
path('captcha/', include('captcha.urls')),
...
]
# 使用CaptchaField在表单中
from django import forms
from captcha.fields import CaptchaField
class ContactForm(forms.Form):
your_name = forms.CharField(label='Your name')
your_email = forms.EmailField(label='Your email')
content = forms.CharField(widget=forms.Textarea, label='Content')
captcha = CaptchaField()
# 在视图中处理表单提交
from django.shortcuts import render
from .forms import ContactForm
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# 处理表单数据
pass
else:
form = ContactForm()
return render(request, 'contact.html', {'form': form})
# 在模板中显示表单
<form method="post" action="">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit">
</form>
以上代码展示了如何在Django项目中安装和使用Django Simple Captcha模块。首先,使用pip安装captcha模块,然后在settings.py中添加captcha应用,运行数据库迁移。接着,在urls.py中添加captcha的URL,并在表单中使用CaptchaField。最后,在视图和模板中处理和显示表单。
评论已关闭