Skip to content

Instantly share code, notes, and snippets.

@AeroNotix
Created April 14, 2012 11:56
Show Gist options
  • Select an option

  • Save AeroNotix/2383873 to your computer and use it in GitHub Desktop.

Select an option

Save AeroNotix/2383873 to your computer and use it in GitHub Desktop.
@json_response
def ajax_add_entry(request):
'''
Adds a calendar entry asynchronously
'''
# create objects to put our data into
json_data = dict()
# object to dump form data into
form = {
'entry_date': None,
'start_time': None,
'end_time': None,
'daytype': None,
}
# get our form data
for key in form:
form[key] = request.POST.get(key, None)
# This should be on the page
shour, sminute = parse_time(form['start_time'])
ehour, eminute = parse_time(form['end_time'])
if (datetime.time(shour, sminute) > datetime.time(ehour, eminute)):
json_data['error'] = "Start time after end time"
return json_data
# need to use sessions
form['user_id'] = 1
# need to add a breaks section to the form
form['breaks'] = "00:15:00"
try:
# this will be ok as soon as I put client side validation
# and server side validation working.
entry = TrackingEntry(**form)
entry.save()
year, month, day = map(int,
form['entry_date'].split("-")
)
# again, sessions
calendar = gen_calendar(year, month, day,
user='aaron.france@hp.com')
except IntegrityError as error:
if error[0] == DUPLICATE_ENTRY:
json_data['error'] = "There is a duplicate entry for this value"
else:
json_data['error'] = str(error)
return json_data
# if all went well
json_data['success'] = True
json_data['calendar'] = calendar
return json_data
def ajax(request):
"""
Ajax request handler, dispatches to specific ajax functions
depending on what json gets sent.
"""
# if the page is accessed via the browser (or other means)
# we don't serve requests
if not request.is_ajax():
raise Http404
# create our JSON object, do we need to do this?
# all the functions return a Dict *and* serialize
# it. We could just leave it to the delegated fun-
# ction to deal with the json.
json_data = {
"success": False,
"error": "",
"calendar": ""
}
# see which form we're dealing with
form_type = request.POST.get('form_type', None)
#if there isn't one, we'll send an error back
if not form_type:
return ajax_error("Missing Form")
try:
# this could be mutated with a @register_ajax
# decorator or something
ajax_funcs = {
'add': ajax_add_entry,
'change': ajax_change_entry,
'delete': ajax_delete_entry
}
return ajax_funcs.get(form_type,
ajax_error("Form not found")
)(request)
# if any errors are sent, let the page deal with it
except Exception as e:
return ajax_error(str(e))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment