Created
April 11, 2024 09:10
-
-
Save christianwgd/81af2fc7a3dbb13d0adc1cf3a609662d to your computer and use it in GitHub Desktop.
Use of django-friendly-captcha in a contact form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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