1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
|
from django import forms
from django.forms.utils import ValidationError
from .validators import validate_email_nouser
from .models import Subscriber, PostcardSubscriber
class SubscribeForm(forms.ModelForm):
class Meta:
model = Subscriber
fields = ['user']
class NewsletterForm(forms.ModelForm):
""" This is the base class for all forms managing subscriptions. """
email_field = forms.EmailField(label='Email Address:', widget=forms.EmailInput(attrs={'placeholder': 'Your email address'}))
class Meta:
model = Subscriber
fields = ('email_field',)
def __init__(self, *args, **kwargs):
assert 'newsletter' in kwargs, 'No newsletter specified'
newsletter = kwargs.pop('newsletter')
if 'ip' in kwargs:
ip = kwargs['ip']
del kwargs['ip']
else:
ip = None
super(NewsletterForm, self).__init__(*args, **kwargs)
self.instance.newsletter = newsletter
if ip:
self.instance.ip = ip
class SubscribeRequestForm(NewsletterForm):
"""
Request subscription to the newsletter. Will result in an activation email
being sent with a link where one can edit, confirm and activate one's
subscription.
"""
email_field = forms.EmailField(
label=("e-mail"), validators=[validate_email_nouser], widget=forms.EmailInput(attrs={'placeholder': 'Your email address'})
)
def clean_email_field(self):
data = self.cleaned_data['email_field']
# Check whether we have already been subscribed to
try:
subscription = Subscriber.objects.get(
email_field__exact=data,
newsletter=self.instance.newsletter
)
if subscription.subscribed and not subscription.unsubscribed:
raise ValidationError(
"I appreciate the effort, but you're already subscribed. (if you're not receiving newsletters, email me at sng@luxagraf.net and I will see what's going on)"
)
else:
self.instance = subscription
self.instance = subscription
except Subscriber.DoesNotExist:
pass
return data
class UpdateForm(NewsletterForm):
"""
This form allows one to actually update to or unsubscribe from the
newsletter. To do this, a correct activation code is required.
"""
email_field = forms.EmailField(
label=("e-mail"), validators=[validate_email_nouser], disabled=True
)
def clean_user_activation_code(self):
data = self.cleaned_data['user_activation_code']
if data != self.instance.activation_code:
raise ValidationError(
('The validation code supplied by you does not match.')
)
return data
user_activation_code = forms.CharField(
label=("Activation code"), max_length=40
)
class PostcardForm(forms.ModelForm):
class Meta:
model = PostcardSubscriber
fields = ['name', 'address']
widgets = {
'address': forms.Textarea(attrs={'rows':3, 'cols':40}),
}
|