forms.py 9.6 KB
Newer Older
1
from django import forms
2
from go.models import URL, RegisteredUser
3
from django.core.exceptions import ValidationError
4
from captcha.fields import CaptchaField
David Haynes's avatar
David Haynes committed
5
from crispy_forms.helper import FormHelper
6 7
from crispy_forms.layout import Layout, Fieldset, Submit, HTML, Div, Field, Button
from crispy_forms.bootstrap import StrictButton, FormActions, PrependedText, Accordion, AccordionGroup, Alert
8 9

class URLForm(forms.ModelForm):
10

11
    # Custom target URL field
12 13 14 15 16
    target = forms.URLField(
        required=True,
        label='Long URL',
        max_length=1000,
        widget=forms.URLInput(attrs={
17
            'placeholder': 'https://'
18 19 20
        })
    )

21
    # Check to make sure the short url has not been used
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
    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,
    )

39 40 41 42 43 44 45 46 47 48 49 50 51 52
    DAY = '1 Day'
    WEEK = '1 Week'
    MONTH = '1 Month'
    NEVER = 'Never'

    EXPIRATION_CHOICES = (
        (DAY, DAY),
        (WEEK, WEEK),
        (MONTH, MONTH),
        (NEVER, NEVER),
    )

    # Add a custom expiration choice field.
    expires = forms.ChoiceField(
53 54 55 56 57
        required=True,
        label='Expiration',
        choices=EXPIRATION_CHOICES,
        initial=NEVER,
        widget=forms.RadioSelect(),
58 59
    )

60 61
    class Meta:
        model = URL
62 63
        fields = ('target',)
        exclude = ('owner', 'short', 'date_created', 'clicks', 'expires')
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 111 112 113 114 115 116 117 118 119


class URLFormTest(forms.ModelForm):

    # Custom target URL field
    target = forms.URLField(
        required=True,
        label='Long URL',
        max_length=1000,
        widget=forms.URLInput(attrs={
        })
    )

    # 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'
    NEVER = 'Never'

    EXPIRATION_CHOICES = (
        (DAY, DAY),
        (WEEK, WEEK),
        (MONTH, MONTH),
        (NEVER, NEVER),
    )

    # Add a custom expiration choice field.
    expires = forms.ChoiceField(
        required=True,
        label='Expiration',
        choices=EXPIRATION_CHOICES,
        initial=NEVER,
        widget=forms.RadioSelect(),
    )

    def __init__(self, *args, **kwargs):
        super(URLFormTest, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
120
        self.helper.form_method = 'POST'
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137

        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-md-1'
        self.helper.field_class = 'col-md-6'


        self.helper.layout = Layout(
            Fieldset(
                '',
                Accordion(
                    AccordionGroup('Step 1: Long URL',
                        Div(
                            HTML("""
                                <h4>Paste the URL you would like to shorten:</h4>
                                <br />
                            """),
                            PrependedText('target',
138
                            'https:// required',
139 140 141 142 143
                            ),
                            style="background: rgb(#F6F6F6);",
                            title="target_url",
                            css_class="first_group",
                        ),
144 145 146
                        css_id='firstCollapse',
                        active=True,
                        template='crispy/accordian-group.html',
147 148 149 150 151
                    ),
                    AccordionGroup('Step 2: Short URL',
                        Div(
                            HTML("""
                                <h4>Create a custom Go address:</h4>
152
                                <br />
153 154 155 156 157 158 159
                            """),
                            PrependedText('short',
                            'go.gmu.edu/',
                            ),
                            style="background: rgb(#F6F6F6);",
                            title="short_url",
                            css_class="second_group",
160 161
                        ),
                        css_id='secondCollapse',
162
                        active=True,
163
                        template='crispy/accordian-group.html',
164 165 166 167 168
                    ),
                    AccordionGroup('Step 3: URL Expiration',
                        Div(
                            HTML("""
                                <h4>Set when you would like your Go address to expire:</h4>
169
                                <br />
170 171 172 173 174
                            """),
                            'expires',
                            style="background: rgb(#F6F6F6);",
                            title="expires_url",
                            css_class="third_group",
175 176
                        ),
                        css_id='thirdCollapse',
177
                        active=True,
178 179 180 181
                        template='crispy/accordian-group.html',
                    ),
                    css_id='accordian',
                    template='crispy/accordian.html'
182 183 184 185
                ),
            HTML("""
                <br />
            """),
186
            StrictButton('Shorten', css_class="btn-success", type='submit'),
187 188 189
        )
    )

190

191 192 193 194 195 196
    class Meta:
        model = URL
        fields = ('target',)
        exclude = ('owner', 'short', 'date_created', 'clicks', 'expires')


197
class SignupForm(forms.ModelForm):
198 199 200 201 202 203 204 205

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

206
    username = forms.CharField(
207 208 209
        required=True,
        label='Mason NetID',
        max_length=30,
210
        validators=[validate_username],
211
        widget=forms.TextInput(attrs={
212 213 214
        }),
    )
    full_name = forms.CharField(
215 216 217 218
        required=True,
        label='Full Name',
        max_length=100,
        widget=forms.TextInput(attrs={
219 220 221
        }),
    )
    description = forms.CharField(
222 223 224 225
        required=False,
        label='Description (Optional)',
        max_length=200,
        widget=forms.Textarea(attrs={
226 227
        }),
    )
228
    captcha = CaptchaField()
229 230 231

    class Meta:
        model = RegisteredUser
232
        fields = '__all__'
David Haynes's avatar
David Haynes committed
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272

class ExampleForm(forms.Form):
    like_website = forms.TypedChoiceField(
        label = "Do you like this website?",
        choices = ((1, "Yes"), (0, "No")),
        coerce = lambda x: bool(int(x)),
        widget = forms.RadioSelect,
        initial = '1',
        required = True,
    )

    favorite_food = forms.CharField(
        label = "What is your favorite food?",
        max_length = 80,
        required = True,
    )

    favorite_color = forms.CharField(
        label = "What is your favorite color?",
        max_length = 80,
        required = True,
    )

    favorite_number = forms.IntegerField(
        label = "Favorite number",
        required = False,
    )

    notes = forms.CharField(
        label = "Additional notes or feedback",
        required = False,
    )
    def __init__(self, *args, **kwargs):
        super(ExampleForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_id = 'id-exampleForm'
        self.helper.form_method = 'post'
        self.helper.form_action = 'submit_survey'

        self.helper.form_class = 'form-horizontal'
273
        self.helper.label_class = 'col-sm-2'
David Haynes's avatar
David Haynes committed
274
        self.helper.field_class = 'col-md-4'
275 276 277 278

        self.helper.help_text_inline = True
        self.helper.error_text_inline = False

David Haynes's avatar
David Haynes committed
279
        self.helper.layout = Layout(
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
            Alert(content='<strong>Warning!</strong> Best check yo self, you\'re not looking too good.'),
            Fieldset(
                'Tell us your favorite stuff {{ request.user.username }}',
                Accordion(
                    AccordionGroup('First Group',
                        Div(
                            HTML("""
                            <h4>Here you select whether you like the website or not:</h4>
                            """),
                            'like_website',
                            style="background: rgb(#F6F6F6);",
                            title="First Group",
                            css_class="first_group",
                        ),
                    ),
                    AccordionGroup('Second Group',
                        PrependedText('favorite_color',
                            'https://',
                            placeholder="www."
                        ),
                    )
                ),
                Field(
                    HTML("""
                    <br />
                    """),
                    'favorite_number',
                    'favorite_food',
                    HTML("""
                    <p>We use notes to get better, <strong>please help us {{ request.user.username }}</strong></p>
                    """),
                    'notes',
                    css_class="inputfields"),
                ),
            FormActions(
                StrictButton('Success', css_class="btn-success"),
            )
David Haynes's avatar
David Haynes committed
317
        )