forms.py 7.67 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
5 6 7 8 9

# App Imports
from go.models import URL, RegisteredUser

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

class URLForm(forms.ModelForm):
17

18 19 20 21 22 23 24 25
    # 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

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

    # 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'
57
    CUSTOM = 'Custom Date'
58 59 60 61 62 63 64
    NEVER = 'Never'

    EXPIRATION_CHOICES = (
        (DAY, DAY),
        (WEEK, WEEK),
        (MONTH, MONTH),
        (NEVER, NEVER),
65
        (CUSTOM, CUSTOM),
66 67
    )

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

Matthew Rodgers's avatar
Matthew Rodgers committed
77
    # Add a custom expiration choice.
78
    expires_custom = forms.DateTimeField(
Matthew Rodgers's avatar
Matthew Rodgers committed
79 80
        required = False,
        label='Custom Date',
81 82 83 84 85 86 87 88 89
        input_formats=['%m-%d-%Y'],
        widget=DateTimePicker(
            options={
                "format": "MM-DD-YYYY",
                "pickTime": False,
                "defaultDate": "4-20-2016",
            },
            icon_attrs={
                "class": "fa fa-calendar",
Matthew Rodgers's avatar
Matthew Rodgers committed
90
            })
91 92
    )

93

94
    def __init__(self, *args, **kwargs):
95 96
        # Grab that host info
        self.host = kwargs.pop('host', None)
97
        super(URLForm, self).__init__(*args, **kwargs)
98
        # Define the basics for crispy-forms
99
        self.helper = FormHelper()
100
        self.helper.form_method = 'POST'
101

102
        # Some xtra vars for form css purposes
103 104 105 106
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-md-1'
        self.helper.field_class = 'col-md-6'

107
        # The main "layout" defined
108
        self.helper.layout = Layout(
109 110
            Fieldset('',
            #######################
111
                Accordion(
112
                    # Step 1: Long URL
113 114 115 116
                    AccordionGroup('Step 1: Long URL',
                        Div(
                            HTML("""
                                <h4>Paste the URL you would like to shorten:</h4>
117
                                <br />"""),
118
                            'target',
119
                            style="background: rgb(#F6F6F6);"),
120
                        active=True,
121 122 123
                        template='crispy/accordian-group.html'),

                    # Step 2: Short URL
124 125 126 127
                    AccordionGroup('Step 2: Short URL',
                        Div(
                            HTML("""
                                <h4>Create a custom Go address:</h4>
128 129 130 131
                                <br />"""),
                            PrependedText(
                            'short', 'https://go.gmu.edu/'),
                            style="background: rgb(#F6F6F6);"),
132
                        active=True,
133 134 135
                        template='crispy/accordian-group.html',),

                    # Step 3: Expiration
136 137 138 139
                    AccordionGroup('Step 3: URL Expiration',
                        Div(
                            HTML("""
                                <h4>Set when you would like your Go address to expire:</h4>
140
                                <br />"""),
141
                            'expires',
142
                            'expires_custom',
143
                            style="background: rgb(#F6F6F6);"),
144
                        active=True,
145
                        template='crispy/accordian-group.html'),
146

147 148 149 150 151 152
                    # FIN
                    template='crispy/accordian.html'),
            #######################
            HTML("""
                <br />"""),
            StrictButton('Shorten', css_class="btn btn-primary btn-md col-md-4", type='submit')))
153

154 155 156 157 158 159
    class Meta:
        model = URL
        fields = ('target',)
        exclude = ('owner', 'short', 'date_created', 'clicks', 'expires')


160
class SignupForm(forms.ModelForm):
161 162 163 164 165 166 167 168

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

169 170 171 172 173 174 175
    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!")
176
        return data_username
177

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

213 214 215 216
    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
217
        self.helper = FormHelper()
218 219 220 221 222
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-md-4'
        self.helper.field_class = 'col-md-6'

        self.helper.layout = Layout(
223
            Fieldset('',
224
                Div(
225
                    # Place in form fields
226 227 228 229 230 231
                    Div(
                        'username',
                        'full_name',
                        'organization',
                        'description',
                        'tos_box',
232 233 234
                        css_class='well'),

                    # Extras at bottom
235
                    StrictButton('Submit',css_class='btn btn-primary btn-md col-md-4', type='submit'),
236
                    css_class='col-md-6')))
237 238
    class Meta:
        model = RegisteredUser
239
        fields = '__all__'