42 lines
1.5 KiB
Python
42 lines
1.5 KiB
Python
from django import forms
|
|
from django.utils.translation import ugettext_lazy as _
|
|
from datacenterlight.utils import get_ip_address
|
|
|
|
import logging
|
|
|
|
from .models import ContactUs
|
|
|
|
import ipaddress
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class ContactForm(forms.ModelForm):
|
|
class Meta:
|
|
fields = ['name', 'email', 'message', 'ip_address']
|
|
model = ContactUs
|
|
labels = {
|
|
"ip_address": _("You are requesting this website from "
|
|
"{{ip_address}}. Enter 'IPv{{v4v6}}':".format(
|
|
ip_address='test', v4v6='4'
|
|
))
|
|
}
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
self.request = kwargs.pop('request', None)
|
|
super(ContactForm, self).__init__(*args, **kwargs)
|
|
self.fields['ip_address'] = forms.CharField(required=True)
|
|
|
|
def clean_ip_address(self):
|
|
input_ip_address_text = self.cleaned_data.get('ip_address')
|
|
request_ip_address = get_ip_address(self.request)
|
|
ip_address_type_text = 'ipv4'
|
|
if (type(ipaddress.ip_address(request_ip_address))
|
|
== ipaddress.IPv4Address):
|
|
ip_address_type_text = 'ipv4'
|
|
elif (type(ipaddress.ip_address(request_ip_address))
|
|
== ipaddress.IPv6Address):
|
|
ip_address_type_text = 'ipv6'
|
|
if input_ip_address_text.strip().lower() == ip_address_type_text:
|
|
return request_ip_address
|
|
else:
|
|
raise forms.ValidationError(_("Input correct IP address type"))
|