forms.py 9.53 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')
37 38
        try:
            final_url = urllib.request.urlopen(target).geturl()
39 40
        # if visiting the provided url results in an HTTP error, or redirects
        # to a page that results in an HTTP error
41 42 43
        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
44
            if any(int(str(e)[11:14]) == errorNum for errorNum in range(300, 308)):
45
                raise ValidationError("Link results in a 300 error")
46 47
            else:
                final_url = ""
48 49
        # if the host (go.gmu.edu) is in the entered target link or where it
        # redirects
50
        if self.host in final_url or self.host in target:
51 52 53 54
            raise ValidationError("You can't make a Go link to Go silly!")
        else:
            return target

55 56 57
    # Custom target URL field
    target = forms.URLField(
        required=True,
58
        label='Long URL (Required)',
59 60
        max_length=1000,
        widget=forms.URLInput(attrs={
61
            'placeholder': 'https://yoursite.com/'
62 63 64
        })
    )

David Haynes's avatar
David Haynes committed
65 66
    # short --------------------------------------------------------------------

67
    def unique_short(value):
David Haynes's avatar
David Haynes committed
68 69 70 71
        """
        Check to make sure the short url has not been used
        """

72
        try:
David Haynes's avatar
David Haynes committed
73
            # if we're able to get a URL with the same short url
74
            URL.objects.get(short__iexact=value)
75
        except URL.DoesNotExist as ex:
76
            return
David Haynes's avatar
David Haynes committed
77

David Haynes's avatar
David Haynes committed
78
        # then raise a ValidationError
79 80 81 82
        raise ValidationError('Short url already exists.')

    # Custom short-url field with validators.
    short = forms.SlugField(
83 84 85 86 87 88
        required=False,
        label='Short URL (Optional)',
        widget=forms.TextInput(),
        validators=[unique_short],
        max_length=20,
        min_length=3,
89 90
    )

David Haynes's avatar
David Haynes committed
91 92 93
    # expires ------------------------------------------------------------------

    # Define some string date standards
94 95 96
    DAY = '1 Day'
    WEEK = '1 Week'
    MONTH = '1 Month'
97
    CUSTOM = 'Custom Date'
98 99
    NEVER = 'Never'

David Haynes's avatar
David Haynes committed
100
    # Define a tuple of string date standards to be used as our date choices
101 102 103 104 105
    EXPIRATION_CHOICES = (
        (DAY, DAY),
        (WEEK, WEEK),
        (MONTH, MONTH),
        (NEVER, NEVER),
106
        (CUSTOM, CUSTOM),
107 108
    )

Matthew Rodgers's avatar
Matthew Rodgers committed
109
    # Add preset expiration choices.
110
    expires = forms.ChoiceField(
111 112 113 114 115
        required=True,
        label='Expiration (Required)',
        choices=EXPIRATION_CHOICES,
        initial=NEVER,
        widget=forms.RadioSelect(),
116 117
    )

Matthew Rodgers's avatar
Matthew Rodgers committed
118
    def valid_date(value):
David Haynes's avatar
David Haynes committed
119 120 121 122
        """
        Check if the selected date is a valid date
        """

David Haynes's avatar
David Haynes committed
123
        # a valid date is one that is greater than today
Matthew Rodgers's avatar
Matthew Rodgers committed
124 125
        if value > timezone.now():
            return
David Haynes's avatar
David Haynes committed
126
        # raise a ValidationError if the date is invalid
Matthew Rodgers's avatar
Matthew Rodgers committed
127
        else:
128
            raise ValidationError('Date must be after today.')
Matthew Rodgers's avatar
Matthew Rodgers committed
129 130


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

149
    def __init__(self, *args, **kwargs):
David Haynes's avatar
David Haynes committed
150 151 152 153
        """
        On initialization of the form, crispy forms renders this layout
        """

154 155
        # Grab that host info
        self.host = kwargs.pop('host', None)
156
        super(URLForm, self).__init__(*args, **kwargs)
157
        # Define the basics for crispy-forms
158
        self.helper = FormHelper()
159
        self.helper.form_method = 'POST'
160

161
        # Some xtra vars for form css purposes
162 163 164 165
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-md-1'
        self.helper.field_class = 'col-md-6'

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

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

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

206 207
                # FIN
                template='crispy/accordian.html'),
208 209 210 211
            #######################
            HTML("""
                <br />"""),
            StrictButton('Shorten', css_class="btn btn-primary btn-md col-md-4", type='submit')))
212

213
    class Meta:
David Haynes's avatar
David Haynes committed
214 215 216 217
        """
        Metadata about this ModelForm
        """

David Haynes's avatar
David Haynes committed
218
        # what model this form is for
219
        model = URL
David Haynes's avatar
David Haynes committed
220
        # what attributes are included
221
        fields = ['target']
222

223
class SignupForm(forms.ModelForm):
224
    """
David Haynes's avatar
David Haynes committed
225
    The form that is used when a user is signing up to be a RegisteredUser
226
    """
227

David Haynes's avatar
David Haynes committed
228
    # The full name of the RegisteredUser
229
    full_name = forms.CharField(
230 231 232 233
        required=True,
        label='Full Name (Required)',
        max_length=100,
        widget=forms.TextInput(),
234
    )
David Haynes's avatar
David Haynes committed
235 236

    # The RegisteredUser's chosen organization
237
    organization = forms.CharField(
238 239 240 241
        required=True,
        label='Organization (Required)',
        max_length=100,
        widget=forms.TextInput(),
242
    )
David Haynes's avatar
David Haynes committed
243 244

    # The RegisteredUser's reason for signing up to us Go
245
    description = forms.CharField(
246 247 248 249
        required=False,
        label='Description (Optional)',
        max_length=200,
        widget=forms.Textarea(),
250
    )
David Haynes's avatar
David Haynes committed
251

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

262
    def __init__(self, request, *args, **kwargs):
David Haynes's avatar
David Haynes committed
263 264 265 266 267 268
        """
        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
269 270
        self.request = request
        super(SignupForm, self).__init__(*args, **kwargs)
David Haynes's avatar
David Haynes committed
271
        self.helper = FormHelper()
272 273 274 275 276
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-md-4'
        self.helper.field_class = 'col-md-6'

        self.helper.layout = Layout(
277
            Fieldset('',
278
                Div(
279
                    # Place in form fields
280 281 282 283
                    Div(
                        'full_name',
                        'organization',
                        'description',
284
                        'registered',
285 286 287
                        css_class='well'),

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

291
    class Meta:
David Haynes's avatar
David Haynes committed
292 293 294 295
        """
        Metadata about this ModelForm
        """

David Haynes's avatar
David Haynes committed
296
        # what model this form is for
297
        model = RegisteredUser
David Haynes's avatar
David Haynes committed
298
        # what attributes are included
299
        fields = ['full_name', 'organization', 'description', 'registered']