forms.py 9.7 KB
Newer Older
1 2 3
# Future Imports
from __future__ import unicode_literals, absolute_import, print_function, division

4
# Python stdlib Imports
David Haynes's avatar
David Haynes committed
5
from datetime import datetime, timedelta
6 7
from six.moves import urllib

8
# Django Imports
9
from django import forms
10
from django.core.exceptions import ValidationError
11
from django.utils.safestring import mark_safe
Matthew Rodgers's avatar
Matthew Rodgers committed
12
from django.utils import timezone
13 14 15 16 17

# App Imports
from go.models import URL, RegisteredUser

# Other Imports
David Haynes's avatar
David Haynes committed
18
from crispy_forms.helper import FormHelper
19 20
from crispy_forms.layout import Layout, Fieldset, Submit, HTML, Div, Field
from crispy_forms.bootstrap import StrictButton, PrependedText, Accordion, AccordionGroup
21
from bootstrap3_datetime.widgets import DateTimePicker
22

23
class URLForm(forms.ModelForm):
24
    """
David Haynes's avatar
David Haynes committed
25
    The form that is used in URL creation.
26
    """
27

David Haynes's avatar
David Haynes committed
28 29
    # target -------------------------------------------------------------------

30
    def clean_target(self):
David Haynes's avatar
David Haynes committed
31 32 33 34
        """
        Prevent redirect loop links
        """

David Haynes's avatar
David Haynes committed
35
        # get the entered target link
36
        target = self.cleaned_data.get('target')
David Haynes's avatar
David Haynes committed
37

38 39
        try:
            final_url = urllib.request.urlopen(target).geturl()
40 41
        # if visiting the provided url results in an HTTP error, or redirects
        # to a page that results in an HTTP error
42 43 44
        except urllib.error.URLError as e:
            # to permit users to enter sites that return most errors, but
            # prevent them from entering sites that result in an HTTP 300 error
45
            if any(int(str(e)[11:14]) == errorNum for errorNum in range(300, 308)):
46
                raise ValidationError("Link results in a 300 error")
47 48
            else:
                final_url = ""
David Haynes's avatar
David Haynes committed
49 50 51 52 53 54 55 56 57 58 59

        # Commented out as this check cannont properly be tested since we cannot
        # dynamically generate request.META.get('HTTP_HOST')

        # # if the host (go.gmu.edu) is in the entered target link or where it
        # # redirects
        # if self.host in final_url or self.host in target:
        #     raise ValidationError("You can't make a Go link to Go silly!")
        # else:
        #     return target
        return target
60

61 62 63
    # Custom target URL field
    target = forms.URLField(
        required=True,
64
        label='Long URL (Required)',
65 66
        max_length=1000,
        widget=forms.URLInput(attrs={
67
            'placeholder': 'https://yoursite.com/'
68 69 70
        })
    )

David Haynes's avatar
David Haynes committed
71 72
    # short --------------------------------------------------------------------

73
    def unique_short(value):
David Haynes's avatar
David Haynes committed
74 75 76 77
        """
        Check to make sure the short url has not been used
        """

78
        try:
David Haynes's avatar
David Haynes committed
79
            # if we're able to get a URL with the same short url
80
            URL.objects.get(short__iexact=value)
81
        except URL.DoesNotExist as ex:
82
            return
David Haynes's avatar
David Haynes committed
83

David Haynes's avatar
David Haynes committed
84
        # then raise a ValidationError
85 86 87 88
        raise ValidationError('Short url already exists.')

    # Custom short-url field with validators.
    short = forms.SlugField(
89 90 91 92 93 94
        required=False,
        label='Short URL (Optional)',
        widget=forms.TextInput(),
        validators=[unique_short],
        max_length=20,
        min_length=3,
95 96
    )

David Haynes's avatar
David Haynes committed
97 98 99
    # expires ------------------------------------------------------------------

    # Define some string date standards
100 101 102
    DAY = '1 Day'
    WEEK = '1 Week'
    MONTH = '1 Month'
103
    CUSTOM = 'Custom Date'
104 105
    NEVER = 'Never'

David Haynes's avatar
David Haynes committed
106
    # Define a tuple of string date standards to be used as our date choices
107 108 109 110 111
    EXPIRATION_CHOICES = (
        (DAY, DAY),
        (WEEK, WEEK),
        (MONTH, MONTH),
        (NEVER, NEVER),
112
        (CUSTOM, CUSTOM),
113 114
    )

Matthew Rodgers's avatar
Matthew Rodgers committed
115
    # Add preset expiration choices.
116
    expires = forms.ChoiceField(
117 118 119 120 121
        required=True,
        label='Expiration (Required)',
        choices=EXPIRATION_CHOICES,
        initial=NEVER,
        widget=forms.RadioSelect(),
122 123
    )

Matthew Rodgers's avatar
Matthew Rodgers committed
124
    def valid_date(value):
David Haynes's avatar
David Haynes committed
125 126 127 128
        """
        Check if the selected date is a valid date
        """

David Haynes's avatar
David Haynes committed
129
        # a valid date is one that is greater than today
Matthew Rodgers's avatar
Matthew Rodgers committed
130 131
        if value > timezone.now():
            return
David Haynes's avatar
David Haynes committed
132
        # raise a ValidationError if the date is invalid
Matthew Rodgers's avatar
Matthew Rodgers committed
133
        else:
134
            raise ValidationError('Date must be after today.')
Matthew Rodgers's avatar
Matthew Rodgers committed
135 136


Matthew Rodgers's avatar
Matthew Rodgers committed
137
    # Add a custom expiration choice.
138
    expires_custom = forms.DateTimeField(
139 140 141 142 143 144
        required=False,
        label='Custom Date',
        input_formats=['%m-%d-%Y'],
        validators=[valid_date],
        initial=lambda: datetime.now() + timedelta(days=1),
        widget=DateTimePicker(
145 146 147 148 149 150
            options={
                "format": "MM-DD-YYYY",
                "pickTime": False,
            },
            icon_attrs={
                "class": "fa fa-calendar",
David Haynes's avatar
David Haynes committed
151 152
            },
        )
153 154
    )

155
    def __init__(self, *args, **kwargs):
David Haynes's avatar
David Haynes committed
156 157 158 159
        """
        On initialization of the form, crispy forms renders this layout
        """

160 161
        # Grab that host info
        self.host = kwargs.pop('host', None)
162
        super(URLForm, self).__init__(*args, **kwargs)
163
        # Define the basics for crispy-forms
164
        self.helper = FormHelper()
165
        self.helper.form_method = 'POST'
166

167
        # Some xtra vars for form css purposes
168 169 170 171
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-md-1'
        self.helper.field_class = 'col-md-6'

172
        # The main "layout" defined
173
        self.helper.layout = Layout(
174 175
            Fieldset('',
            #######################
176
                Accordion(
177
                    # Step 1: Long URL
178 179 180 181
                    AccordionGroup('Step 1: Long URL',
                        Div(
                            HTML("""
                                <h4>Paste the URL you would like to shorten:</h4>
182
                                <br />"""),
183
                            'target',
184 185 186
                        style="background: rgb(#F6F6F6);"),
                    active=True,
                    template='crispy/accordian-group.html'),
187 188

                    # Step 2: Short URL
189 190 191 192
                    AccordionGroup('Step 2: Short URL',
                        Div(
                            HTML("""
                                <h4>Create a custom Go address:</h4>
193 194
                                <br />"""),
                            PrependedText(
195
                            'short', 'https://go.gmu.edu/', template='crispy/customPrepended.html'),
196 197 198
                        style="background: rgb(#F6F6F6);"),
                    active=True,
                    template='crispy/accordian-group.html',),
199 200

                    # Step 3: Expiration
201 202 203 204
                    AccordionGroup('Step 3: URL Expiration',
                        Div(
                            HTML("""
                                <h4>Set when you would like your Go address to expire:</h4>
205
                                <br />"""),
206
                            'expires',
207
                            Field('expires_custom', template="crispy/customDateField.html"),
208 209 210
                        style="background: rgb(#F6F6F6);"),
                    active=True,
                    template='crispy/accordian-group.html'),
211

212 213
                # FIN
                template='crispy/accordian.html'),
214 215 216 217
            #######################
            HTML("""
                <br />"""),
            StrictButton('Shorten', css_class="btn btn-primary btn-md col-md-4", type='submit')))
218

219
    class Meta:
David Haynes's avatar
David Haynes committed
220 221 222 223
        """
        Metadata about this ModelForm
        """

David Haynes's avatar
David Haynes committed
224
        # what model this form is for
225
        model = URL
David Haynes's avatar
David Haynes committed
226
        # what attributes are included
227
        fields = ['target']
228

229
class SignupForm(forms.ModelForm):
230
    """
David Haynes's avatar
David Haynes committed
231
    The form that is used when a user is signing up to be a RegisteredUser
232
    """
233

David Haynes's avatar
David Haynes committed
234
    # The full name of the RegisteredUser
235
    full_name = forms.CharField(
236 237 238 239
        required=True,
        label='Full Name (Required)',
        max_length=100,
        widget=forms.TextInput(),
240
    )
David Haynes's avatar
David Haynes committed
241 242

    # The RegisteredUser's chosen organization
243
    organization = forms.CharField(
244 245 246 247
        required=True,
        label='Organization (Required)',
        max_length=100,
        widget=forms.TextInput(),
248
    )
David Haynes's avatar
David Haynes committed
249 250

    # The RegisteredUser's reason for signing up to us Go
251
    description = forms.CharField(
252 253 254 255
        required=False,
        label='Description (Optional)',
        max_length=200,
        widget=forms.Textarea(),
256
    )
David Haynes's avatar
David Haynes committed
257

258 259
    # A user becomes registered when they agree to the TOS
    registered = forms.BooleanField(
260
        required=True,
David Haynes's avatar
David Haynes committed
261 262
        # ***Need to replace lower url with production URL***
        # ie. go.gmu.edu/about#terms
263 264 265
        label=mark_safe(
            'Do you accept the <a href="http://127.0.0.1:8000/about#terms">Terms of Service</a>?'
        ),
266 267
    )

268
    def __init__(self, request, *args, **kwargs):
David Haynes's avatar
David Haynes committed
269 270 271 272 273 274
        """
        On initialization of the form, crispy forms renders this layout
        """

        # Necessary to call request in forms.py, is otherwise restricted to
        # views.py and models.py
275 276
        self.request = request
        super(SignupForm, self).__init__(*args, **kwargs)
David Haynes's avatar
David Haynes committed
277
        self.helper = FormHelper()
278 279 280 281 282
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-md-4'
        self.helper.field_class = 'col-md-6'

        self.helper.layout = Layout(
283
            Fieldset('',
284
                Div(
285
                    # Place in form fields
286 287 288 289
                    Div(
                        'full_name',
                        'organization',
                        'description',
290
                        'registered',
291 292 293
                        css_class='well'),

                    # Extras at bottom
294
                    StrictButton('Submit',css_class='btn btn-primary btn-md col-md-4', type='submit'),
295
                    css_class='col-md-6')))
David Haynes's avatar
David Haynes committed
296

297
    class Meta:
David Haynes's avatar
David Haynes committed
298 299 300 301
        """
        Metadata about this ModelForm
        """

David Haynes's avatar
David Haynes committed
302
        # what model this form is for
303
        model = RegisteredUser
David Haynes's avatar
David Haynes committed
304
        # what attributes are included
305
        fields = ['full_name', 'organization', 'description', 'registered']