Skip to content

Instantly share code, notes, and snippets.

@christianwgd
Created April 11, 2024 09:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christianwgd/81af2fc7a3dbb13d0adc1cf3a609662d to your computer and use it in GitHub Desktop.
Save christianwgd/81af2fc7a3dbb13d0adc1cf3a609662d to your computer and use it in GitHub Desktop.
Use of django-friendly-captcha in a contact form
# -*- coding: utf-8 -*-
import re
from django import forms
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from friendly_captcha.fields import FrcCaptchaField
from contact.models import Filter, ContactMessage
class ContactForm(forms.ModelForm):
class Meta:
model = ContactMessage
fields = (
'name', 'email', 'subject', 'text'
)
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
if getattr(settings, 'CONTACT_USE_HONEYPOT', False):
self.fields['comment'] = forms.CharField(
label=_('comment'),
max_length=100,
required=False
)
self.Meta.fields += ('comment',)
if getattr(settings, 'CONTACT_USE_CAPTCHA', False):
captcha = FrcCaptchaField()
def clean_subject(self):
""" Check subject for unwanted content to avoid spam """
subject = self.cleaned_data['subject']
for filter in Filter.objects.all():
if re.search(filter.regex, subject, re.IGNORECASE) is not None:
raise forms.ValidationError(filter.errormsg, code='invalid_content')
return subject
def clean_text(self):
""" Check message for unwanted content to avoid spam """
text = self.cleaned_data['text']
for filter in Filter.objects.all():
if re.search(filter.regex, text, re.IGNORECASE) is not None:
raise forms.ValidationError(filter.errormsg, code='invalid_content')
return text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment