forms.py 8.07 KB
Newer Older
1
# Django Imports
2
from django import forms
3
from django.core.exceptions import ValidationError
4
from django.utils.safestring import mark_safe
Matthew Rodgers's avatar
Matthew Rodgers committed
5
from django.utils import timezone
6 7 8 9 10

# App Imports
from go.models import URL, RegisteredUser

# Other Imports
David Haynes's avatar
David Haynes committed
11
from crispy_forms.helper import FormHelper
12 13
from crispy_forms.layout import Layout, Fieldset, Submit, HTML, Div, Field
from crispy_forms.bootstrap import StrictButton, PrependedText, Accordion, AccordionGroup
14
from bootstrap3_datetime.widgets import DateTimePicker
15
import datetime
Matthew Rodgers's avatar
Matthew Rodgers committed
16
from datetime import date
17 18

class URLForm(forms.ModelForm):
19

20 21 22 23 24 25 26 27
    # Prevent redirect loop links
    def clean_target(self):
        target = self.cleaned_data.get('target')
        if self.host in target:
            raise ValidationError("You can't make a Go link to Go silly!")
        else:
            return target

28 29 30
    # Custom target URL field
    target = forms.URLField(
        required=True,
31
        label='Long URL (Required)',
32 33
        max_length=1000,
        widget=forms.URLInput(attrs={
34
            'placeholder': 'https://yoursite.com/'
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
        })
    )

    # Check to make sure the short url has not been used
    def unique_short(value):
        try:
            URL.objects.get(short__iexact=value)
        except URL.DoesNotExist:
            return
        raise ValidationError('Short url already exists.')

    # Custom short-url field with validators.
    short = forms.SlugField(
        required=False,
        label='Short URL (Optional)',
        widget=forms.TextInput(),
        validators=[unique_short],
        max_length=20,
        min_length=3,
    )

    DAY = '1 Day'
    WEEK = '1 Week'
    MONTH = '1 Month'
59
    CUSTOM = 'Custom Date'
60 61 62 63 64 65 66
    NEVER = 'Never'

    EXPIRATION_CHOICES = (
        (DAY, DAY),
        (WEEK, WEEK),
        (MONTH, MONTH),
        (NEVER, NEVER),
67
        (CUSTOM, CUSTOM),
68 69
    )

Matthew Rodgers's avatar
Matthew Rodgers committed
70
    # Add preset expiration choices.
71 72
    expires = forms.ChoiceField(
        required=True,
73
        label='Expiration (Required)',
74 75 76 77 78
        choices=EXPIRATION_CHOICES,
        initial=NEVER,
        widget=forms.RadioSelect(),
    )

Matthew Rodgers's avatar
Matthew Rodgers committed
79 80 81 82 83 84 85
    def valid_date(value):
        if value > timezone.now():
            return
        else:
            raise ValidationError('Date can\'t be before today.')


Matthew Rodgers's avatar
Matthew Rodgers committed
86
    # Add a custom expiration choice.
87
    expires_custom = forms.DateTimeField(
Matthew Rodgers's avatar
Matthew Rodgers committed
88 89
        required = False,
        label='Custom Date',
90
        input_formats=['%m-%d-%Y'],
Matthew Rodgers's avatar
Matthew Rodgers committed
91
        validators=[valid_date],
92 93 94 95
        widget=DateTimePicker(
            options={
                "format": "MM-DD-YYYY",
                "pickTime": False,
96
                "defaultDate": (datetime.date.today() + datetime.timedelta(hours=24)).strftime("%m-%d-%Y"),
97 98 99
            },
            icon_attrs={
                "class": "fa fa-calendar",
Matthew Rodgers's avatar
Matthew Rodgers committed
100
            })
101 102
    )

103
    def __init__(self, *args, **kwargs):
104 105
        # Grab that host info
        self.host = kwargs.pop('host', None)
106
        super(URLForm, self).__init__(*args, **kwargs)
107
        # Define the basics for crispy-forms
108
        self.helper = FormHelper()
109
        self.helper.form_method = 'POST'
110

111
        # Some xtra vars for form css purposes
112 113 114 115
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-md-1'
        self.helper.field_class = 'col-md-6'

116
        # The main "layout" defined
117
        self.helper.layout = Layout(
118 119
            Fieldset('',
            #######################
120
                Accordion(
121
                    # Step 1: Long URL
122 123 124 125
                    AccordionGroup('Step 1: Long URL',
                        Div(
                            HTML("""
                                <h4>Paste the URL you would like to shorten:</h4>
126
                                <br />"""),
127
                            'target',
128
                            style="background: rgb(#F6F6F6);"),
129
                        active=True,
130 131 132
                        template='crispy/accordian-group.html'),

                    # Step 2: Short URL
133 134 135 136
                    AccordionGroup('Step 2: Short URL',
                        Div(
                            HTML("""
                                <h4>Create a custom Go address:</h4>
137 138
                                <br />"""),
                            PrependedText(
139
                            'short', 'https://go.gmu.edu/', template='crispy/customPrepended.html'),
140
                            style="background: rgb(#F6F6F6);"),
141
                        active=True,
142 143 144
                        template='crispy/accordian-group.html',),

                    # Step 3: Expiration
145 146 147 148
                    AccordionGroup('Step 3: URL Expiration',
                        Div(
                            HTML("""
                                <h4>Set when you would like your Go address to expire:</h4>
149
                                <br />"""),
150
                            'expires',
151
                            Field('expires_custom', template="crispy/customDateField.html"),
152
                            style="background: rgb(#F6F6F6);"),
153
                        active=True,
154
                        template='crispy/accordian-group.html'),
155

156 157 158 159 160 161
                    # FIN
                    template='crispy/accordian.html'),
            #######################
            HTML("""
                <br />"""),
            StrictButton('Shorten', css_class="btn btn-primary btn-md col-md-4", type='submit')))
162

163 164 165 166 167 168
    class Meta:
        model = URL
        fields = ('target',)
        exclude = ('owner', 'short', 'date_created', 'clicks', 'expires')


169
class SignupForm(forms.ModelForm):
170 171 172 173 174 175 176 177

    def validate_username(username):
        try:
            registered = RegisteredUser.objects.get(username=username)
            raise ValidationError('Username "%s" is already in use.' % username)
        except RegisteredUser.DoesNotExist:
            return

178 179 180 181 182 183 184
    def clean_username(self):
        # Prevent hax: (non-staff) Users cannot signup for other users
        data_username = self.cleaned_data.get("username")

        if not self.request.user.is_staff:
            if self.request.user.username not in data_username:
                raise ValidationError('username', "This is not your NetID!")
185
        return data_username
186

187
    username = forms.CharField(
188
        required=True,
189
        label='Mason NetID (Required)',
190
        max_length=30,
191
        validators=[validate_username],
192
        widget=forms.TextInput(attrs={
193 194 195
        }),
    )
    full_name = forms.CharField(
196
        required=True,
197
        label='Full Name (Required)',
198 199
        max_length=100,
        widget=forms.TextInput(attrs={
200 201
        }),
    )
202 203 204 205 206 207 208
    organization = forms.CharField(
        required=True,
        label='Organization (Required)',
        max_length=100,
        widget=forms.TextInput(attrs={
        })
    )
209
    description = forms.CharField(
210 211 212 213
        required=False,
        label='Description (Optional)',
        max_length=200,
        widget=forms.Textarea(attrs={
214 215
        }),
    )
216 217
    tos_box = forms.BooleanField(
        required=True,
218
        # Need to add a Terms of Service Page and replace the href below
219 220 221
        label = mark_safe('Do you accept the <a href="#" target="_blank">Terms of Service</a>?'),
    )

222 223 224 225
    def __init__(self, request, *args, **kwargs):
        # Necessary to call request in forms.py, is otherwise restricted to views.py and models.py
        self.request = request
        super(SignupForm, self).__init__(*args, **kwargs)
David Haynes's avatar
David Haynes committed
226
        self.helper = FormHelper()
227 228 229 230 231
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-md-4'
        self.helper.field_class = 'col-md-6'

        self.helper.layout = Layout(
232
            Fieldset('',
233
                Div(
234
                    # Place in form fields
235 236 237 238 239 240
                    Div(
                        'username',
                        'full_name',
                        'organization',
                        'description',
                        'tos_box',
241 242 243
                        css_class='well'),

                    # Extras at bottom
244
                    StrictButton('Submit',css_class='btn btn-primary btn-md col-md-4', type='submit'),
245
                    css_class='col-md-6')))
246 247
    class Meta:
        model = RegisteredUser
248
        fields = '__all__'