format data in views.py for ajax - django

I'me trying to use this eventCalendar in django : http://jquery-week-calendar.googlecode.com/svn/trunk/jquery.weekcalendar/full_demo/weekcalendar_full_demo.html
I suppose to write ajax codes myself but on the other hand I'me a newbie in jquery ajax,I wanna send event data include startTime,endTime,etc to show them on the calendar:
$('#calendar').weekCalendar({
data: function(callback){
$.getJSON("{% url DrHub.views.getEvents %}",
{
},
function(result) {
callback(result);
}
);
}
});
this calendar get data in this format:
return {
events : [
{
"id":1,
"start": new Date(year, month, day, 12),
"end": new Date(year, month, day, 13, 30),
"title":"Lunch with Mike"
},
{
"id":2,
"start": new Date(year, month, day, 14),
"end": new Date(year, month, day, 14, 45),
"title":"Dev Meeting"
},
...
]
};
how can I format fetched data from database in getEvents view?

from django.utils import simplejson
def some_view(request):
# Build the output -> it's a standard Python dict
output = {
"events": [
{
"id": 1,
"start": "2009-05-10T13:15:00.000+10:00",
"end": "2009-05-10T14:15:00.000+10:00",
"title":"Lunch with Mike"
},
]
}
# With db data you would do something like:
# events = Event.objects.all()
# for event in events:
# event_out = {
# "title": event.title,
# # other fields here
# }
# output['events'].append(event_out)
# Return the output as JSON
return HttpResponse(simplejson.dumps(output), mimetype='application/json')

You can construct the dictionary as usual, just take into account that strings for dates will not be interpreted in javascript without processing. My advice is to directly send javascript interpretable dates, not strings, as follows:
from django.utils import simplejson
import datetime
import time
occ.start = time.mktime(occ.start.timetuple())*1000
occ.end = time.mktime(occ.end.timetuple())*1000
event = {'id': occ.id,'title':occ.title,'start':occ.start,'end':occ.end,'body':occ.description,'readOnly': '%r' %occ.read_only,'recurring':'%r' % occ.recurring,'persisted': '%r' % occ.persisted,'event_id':occ.event.id}
mimetype = 'application/json'
return HttpResponse(simplejson.dumps(event),mimetype)
take into account that the calendar expects the 'events' key so:
$.getJSON(url, function(data){
res = {events:data};
//alert(JSON.stringify(res, null, 4));
callback(res);
});
If you preffer processing on the javascript side try the library datejs that can convert a date from text.

Related

Question about Google Calendar API and create multiple Calendars

I would like to create a script in python that creates events for me for each individual user, I know how to get the list of calendars, but I would like the script to check if there is already a calendar available with that user name and if there isn't one, it creates one, in a way.
Thanks
from datetime import datetime, timedelta
from cal_setup import get_calendar_service
currentDateTime = datetime.now()
userfinder = 'Tuxone'
#Create a new calendar
calendar_name = userfinder
calendar = {
'summary': calendar_name,
'timeZone': 'America/Los_Angeles'
}
created_calendar = get_calendar_service().calendars().insert(body=calendar).execute()
#Print calendar list
# # calendar_list_entry = get_calendar_service().calendarList().get(calendarId=created_calendar['id']).execute()
# # print(calendar_list_entry)
def main():
# creates one hour event tomorrow 10 AM IST
service = get_calendar_service()
d = datetime.now().date()
tomorrow = datetime(d.year, d.month, d.day, 10)+timedelta(days=1)
start = tomorrow.isoformat()
end = (tomorrow + timedelta(hours=1)).isoformat()
event_result = service.events().insert(calendarId='ici1sgh7untsn7650edoknqblk#group.calendar.google.com',
body={
"summary": f'{currentDateTime}',
"description": 'This is a tutorial example of automating google calendar with python',
"start": {"dateTime": start, "timeZone": 'Asia/Kolkata'},
"end": {"dateTime": end, "timeZone": 'Asia/Kolkata'},
}
).execute()
print("created event")
print("id: ", event_result['id'])
print("summary: ", event_result['summary'])
print("starts at: ", event_result['start']['dateTime'])
print("ends at: ", event_result['end']['dateTime'])
if __name__ == '__main__':
main()

Django Server Side set-up for pagination with Datatable

I am using Django for backend, and I am using Datatable library to display a large number of records ( approx 1 million records ). I am trying to set up datatable in such a way that
every time 25 records are being fetched from the backend and when the user clicks on the next page button, another ajax call gets the next 25 records and so on.
But I am having a trouble setting these up.
My DataTable initialisation :
$("#company-table").DataTable({
"processing": true,
"serverSide": true,
"bDestroy": true,
ajax: {
type: "POST",
url: "/get_results/",
headers: {
"X-CSRFToken": getCookie("csrftoken"),
},
data: {
...other data params...
page:$("#company-table").DataTable().page()
},
},
columns: [
...populating columns...
],
});
And my views.py looks like this ( It is completely wrong as far as I know ) :
#filtered_queryset contains all the records.
paginator = Paginator(filtered_queryset, 25) # Show 25 contacts per page.
page_number = request.POST.get('page')
start = request.POST.get('start')
length = request.POST.get('length')
page_obj = paginator.get_page(page_number)
data = list(page_obj.object_list.values())
return_data = {"data": data}
json_data = json.dumps(return_data,indent=4, sort_keys=True, default=str)
return HttpResponse (json_data, content_type = "application/json")
Can anyone help me? Or just nudge me in the right direction?
Try this one django-ajax-datatable
I hope this will work

Using views to change DRF response

I would like to alter the response from an API.
However, it does not alter the result properly. I get a KeyError: 'game'.
I am not sure why, as my API response (via URL) seems to have the value game in it. I may be getting confused with the JSON response, and the python object.
I have a sample of the API response below
results from API
{
"pk": 995,
"game": [
{
"name": "Finance",
"gamelevel": 3
},
{
"name": "Data",
"gamelevel": 1
}
]
},
views.py
class TagList(viewsets.ModelViewSet):
queryset = Task.objects.filter(game__isnull=False).all()
serializer_class = TagSortSerializer
def get_queryset(self):
test = self.queryset.values('title', 'game__name')
result = defaultdict(set)
for item in queryset:
parent = {'name': 'NoLevel_1'}
children = []
for game in item['game']:
if game['gamelevel'] == 1:
parent = game
else:
children.append((game['gamelevel'], game['name']))
result[parent['name']].update(children)
result = [
{
'name': parent,
'game_child': [
{'name': name, 'gamelevel': gamelevel} for gamelevel, name in games
],
'gamelevel': 1,
} for parent, games in result.items()
]
return result
You're using the values queryset method to get only a selection of fields from the model, and the only fields you've specified are title and tag__name. So you won't get game or any of the other keys you've used.
You certainly don't want to use values here in the first place; just do a normal query and access fields via dot lookup rather than dictionary.

Creating multiple events in office365 rest api

I have below code which posts one calendar event to the events on office 365 REST API. I need to enter about 100 events to my calendar. Is there any way to place multiple events in the json data or should I use for loop?
import urllib2
import getpass
import os
import json
import sys
import base64
# Set the request parameters
url = 'https://outlook.office365.com/api/v1.0/me/events?$Select=Start,End'
user = 'emailuser#email.com'
pwd = getpass.getpass('Please enter your AD password: ')
# Create JSON payload
data = {
"Subject": "My Subject",
"Body": {
"ContentType": "HTML",
"Content": ""
},
"Start": "2015-08-11T07:00:00-05:00",
"StartTimeZone": "Central Standard Time",
"End": "2015-08-11T15:00:00-05:00",
"EndTimeZone": "Central Standard Time",
}
json_payload = json.dumps(data)
# Build the HTTP request
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request(url, data=json_payload)
auth = base64.encodestring('%s:%s' % (user, pwd)).replace('\n', '')
request.add_header('Authorization', 'Basic %s' % auth)
request.add_header('Content-Type', 'application/json')
request.add_header('Accept', 'application/json')
request.get_method = lambda: 'POST'
# Perform the request
result = opener.open(request)
Batch processing is on our road map, but it isn't there today.
I ended up making function to create one event at a time and call the function on each iteration:
def create_event(date1, date2):
# Create JSON payload
data = {
"Subject": admin.longname,
"Body": {
"ContentType": "HTML",
"Content": ""
},
"Start": date1,
"StartTimeZone": "Central Standard Time",
"End": date2,
"EndTimeZone": "Central Standard Time",
}
json_payload = json.dumps(data)
# Build the HTTP request
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request(url, data=json_payload)
auth = base64.encodestring('%s:%s' % (user, pwd)).replace('\n', '')
request.add_header('Authorization', 'Basic %s' % auth)
request.add_header('Content-Type', 'application/json')
request.add_header('Accept', 'application/json')
request.get_method = lambda: 'POST'
# Perform the request
result = opener.open(request)
def A( weeka, weekb ):
today = datetime.date.today()
firstday = today + relativedelta(weekday=SU(+ weeka))
for i in range(5):
firstday += datetime.timedelta(days=1)
date1 = '%sT07:00:00-05:00' % firstday
date2 = '%sT16:00:00-05:00' % firstday
create_event(date1, date2)
A(1,2)

Right way to pass Django objects to ExtJS

Django has a built in serialization functionality which allows you to serialize any query result set into JSON:
json_serializer = serializers.get_serializer("json")()
json_serializer.serialize(queryset, ensure_ascii=False)
This produces output such as:
[
{
"pk": 1,
"model": "app_name.model_name",
"fields": {
"field_name": "value",
(...)
}
}
]
If you want to pass this JSON object over to an ExtJS driven application you run into a problem, because ExtJS expects its JSON to be formatted differently:
{
"total": 100,
"success": true,
"objects": [
{
"id": 1,
"field_name": "value",
(...)
}
]
}
There are 2 main differences: the additional meta-data (success, total) and the IDs of the objects which are provided together with other fields in Ext, but not in Django.
There are many possible ways to make one or the other format conform with the second, but what do you consider to be the best way to make this work? Is it a special serializer on the Django side, or maybe a special reader on the ExtJS side...
What do you think is the best way to solve this problem?
Better idea: use a custom serialiser.
settings.py
SERIALIZATION_MODULES = {
'extjson': 'extjs.serialiser.json'
}
extjs\serialiser\json.py
from django.core.serialisers.json import Serialiser
class ExtJSONSerialiser(Serializer)
"""
Serializes a QuerySet to basic Python objects.
"""
def end_object(self, obj):
self._current.update({"id": smart_unicode(obj._get_pk_val(), strings_only=True),})
self.objects.append(self._current)
self._current = None
def getvalue(self):
return {
'total': len(self.objects),
'success': True,
'objects': self.objects,
}
yourcode.py
json_serializer = serializers.get_serializer("extjson")()
json_serializer.serialize(queryset, ensure_ascii=False)
I found a solution which is able to serialize objects, which contain QuerySet as attributes. It's comes from traddicts.org blog, but you can now find it on GitHub:
https://github.com/datamafia/django-query-json-serializer/blob/master/JSONSerializer.py
I further modified the code to work recursively, so in effect I can do the following:
users = User.objects.all()
response = {}
response['success'] = True
response['users'] = users
json_serialize(response)
json_serialize(response, serialize_related=True)
json_serialize(response, serialize_related=True, ignored=['users.groups'])
json_serialize(response, serialize_related=True, ignored=['users.groups.permissions'])
I like your answer Thomas, but I needed something which would be even more flexible.