Commit 6e4f7595 authored by David Haynes's avatar David Haynes 🙆
Browse files

New Forms classes for testing and refrence

- /test goes to new address creation
- forms. wrapped in bacon and deep fried. nice and crispy!
parent 5d6e235d
......@@ -3,8 +3,8 @@ from go.models import URL, RegisteredUser
from django.core.exceptions import ValidationError
from captcha.fields import CaptchaField
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Fieldset, ButtonHolder, Submit
from crispy_forms.bootstrap import StrictButton
from crispy_forms.layout import Layout, Fieldset, Submit, HTML, Div, Field, Button
from crispy_forms.bootstrap import StrictButton, FormActions, PrependedText, Accordion, AccordionGroup, Alert
class URLForm(forms.ModelForm):
......@@ -62,6 +62,130 @@ class URLForm(forms.ModelForm):
fields = ('target',)
exclude = ('owner', 'short', 'date_created', 'clicks', 'expires')
class URLFormTest(forms.ModelForm):
# Custom target URL field
target = forms.URLField(
required=True,
label='Long URL',
max_length=1000,
widget=forms.URLInput(attrs={
'placeholder': 'https://'
})
)
# 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()
self.helper.form_id = 'id-URLFormTest'
self.helper.form_method = 'post'
self.helper.form_action = 'submit_URLTest'
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'col-md-1'
self.helper.field_class = 'col-md-6'
self.helper.help_text_inline = True
self.helper.error_text_inline = False
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',
'https://',
placeholder="www."
),
style="background: rgb(#F6F6F6);",
title="target_url",
css_class="first_group",
),
),
AccordionGroup('Step 2: Short URL',
Div(
HTML("""
<h4>Create a custom Go address:</h4>
"""),
PrependedText('short',
'go.gmu.edu/',
),
style="background: rgb(#F6F6F6);",
title="short_url",
css_class="second_group",
)
),
AccordionGroup('Step 3: URL Expiration',
Div(
HTML("""
<h4>Set when you would like your Go address to expire:</h4>
"""),
'expires',
style="background: rgb(#F6F6F6);",
title="expires_url",
css_class="third_group",
)
)
),
HTML("""
<br />
"""),
StrictButton('Shorten', css_class="btn-success"),
)
)
class Meta:
model = URL
fields = ('target',)
exclude = ('owner', 'short', 'date_created', 'clicks', 'expires')
class SignupForm(forms.ModelForm):
def validate_username(username):
......@@ -138,13 +262,48 @@ class ExampleForm(forms.Form):
self.helper.form_action = 'submit_survey'
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'col-md-4'
self.helper.label_class = 'col-sm-2'
self.helper.field_class = 'col-md-4'
self.helper.help_text_inline = True
self.helper.error_text_inline = False
self.helper.layout = Layout(
'like_website',
'favorite_food',
'favorite_color',
'favorite_number',
'notes',
StrictButton('Sign in', css_class='btn-default'),
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"),
)
)
......@@ -10,20 +10,18 @@ Go - A Product of Vapor
<style>
.asteriskField {
display: none;
}
}
</style>
<div class="page-header" id="banner">
<div class="row">
<div class="col-md-12">
<h1><strong>Super secret testing page</strong></h1>
<h1><strong>Shorten URL</strong></h1>
</div>
</div>
</div>
{% crispy form form.helper %}
{% crispy form %}
<div id='form-errors'>{{ form_errors }}</div>
{% endblock %}
from go.models import URL, RegisteredUser
from go.forms import URLForm, SignupForm, ExampleForm
from go.forms import URLForm, SignupForm, ExampleForm, URLFormTest
from datetime import timedelta
from django.conf import settings
from django.http import HttpResponseServerError # Http404
......@@ -69,16 +69,74 @@ def error_500(request):
return render(request, '500.html', {
},
)
def test(request):
"""
Testing page, pls ignore.
"""
url_form = ExampleForm()
# If the user is not authenticated, show them a public landing page.
if not request.user.is_authenticated():
return render(request, 'public_landing.html')
# If the user isn't registered, don't give them any leeway.
if not is_approved(request.user):
return render(request, 'not_registered.html')
url_form = URLFormTest() # unbound form
if request.method == 'POST':
url_form = URLForm(request.POST) # bind dat form
url_form = URLFormTest(request.POST) # bind dat form
if url_form.is_valid():
# We don't commit the url object yet because we need to add its
# owner, and parse its date field.
url = url_form.save(commit=False)
url.owner = request.user
# If the user entered a short url, it's already been validated,
# so accept it. If they did not, however, then generate a
# random one and use that instead.
short = url_form.cleaned_data.get('short').strip()
if len(short) > 0:
url.short = short
else:
# If the user didn't enter a short url, generate a random
# one. However, if a random one can't be generated, return
# a 500 server error.
random_short = URL.generate_valid_short()
if random_short is None:
return HttpResponseServerError(
render(request, '500.html', {})
)
else:
url.short = random_short
# Grab the expiration field value. It's currently an unsable
# string value, so we need to parse it into a datetime object
# relative to right now.
expires = url_form.cleaned_data.get('expires')
if expires == URLFormTest.DAY:
url.expires = timezone.now() + timedelta(days=1)
elif expires == URLFormTest.WEEK:
url.expires = timezone.now() + timedelta(weeks=1)
elif expires == URLFormTest.MONTH:
url.expires = timezone.now() + timedelta(weeks=3)
else:
pass # leave the field NULL
# Make sure that our new URL object is clean, then save it and
# let's redirect to view this baby.
url.full_clean()
url.save()
return redirect('view', url.short)
return render(request, 'test.html', {
'form': url_form,
},)
},
)
##############################################################################
"""
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment