2
votes

As a start I wanted to view my events from google calendar in Django, I tried the quickstart example, run successfully, after installing the google-api-python-client and downloading the json file.

I followed the Google's example page, the sample didn't seem to work, I got this error when running python manage.py makemigrations:

"Must specify either GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, or "django.core.exceptions.ImproperlyConfigured: Must specify either GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, or both GOOGLE_OAUTH2_CLIENT_ID and GOOGLE_OAUTH2_CLIENT_SECRET in settings.py

Even after I commented GOOGLE_OAUTH2_CLIENT_ID and GOOGLE_OAUTH2_CLIENT_SECRET from settings.py

views.py:

CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), '..', 'client_secret.json')

FLOW = flow_from_clientsecrets(
CLIENT_SECRETS,
scope='https://www.googleapis.com/auth/calendar.readonly',
redirect_uri='http://www.notify-me.ua:8000/complete/google-oauth2/')


@login_required
def home(request):
    storage = Storage(CredentialsModel, 'id', request.user, 'credential')
    credential = storage.get()
    if credential is None or credential.invalid == True:
        FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY,
                    request.user)
        authorize_url = FLOW.step1_get_authorize_url()
        return HttpResponseRedirect(authorize_url)
    else:
        http = httplib2.Http()
        http = credential.authorize(http)
        service = build("calendar", "v3", http=http)

        now = datetime.datetime.utcnow().isoformat() + 'Z'
        eventsResult = service.events()

        return render(request, 'home.html', {
            'eventsResult': eventsResult,
            })

@login_required
def auth_return(request):
    if not xsrfutil.validate_token(settings.SECRET_KEY, request.REQUEST['state'], request.user):
        return HttpResponseBadRequest()
    credential = FLOW.step2_exchange(request.REQUEST)
    storage = Storage(CredentialsModel, 'id', request.user, 'credential')
    storage.put(credential)
    return HttpResponseRedirect("/")

models.py:

from django.db import models
from django.contrib.auth.models import User
from oauth2client.contrib.django_util.models import CredentialsField

class CredentialsModel(models.Model):
    id = models.ForeignKey(User, primary_key=True)
    credential = CredentialsField()

I want to simply view my events from google calendar.

2

2 Answers

3
votes

I was getting the error because there was a line missing in my settings.py:

GOOGLE_OAUTH2_CLIENT_SECRETS_JSON = 'client_secret.json'

Everything else is in the docs.

1
votes

The related SO question already shows how to print it in the page (by getting the response of the function) and insert to the calendar using service.events().insert. The document about Calendars and Events can help you understand how to insert, delete, get, patch or update a calendar metadata. Events: insert Class provides basic properties and option properties when creating an event.

start_datetime = datetime.datetime.now(tz=pytz.utc)
event = service.events().insert(calendarId='<YOUR EMAIL HERE>@gmail.com', body={
'summary': 'Foo',
'description': 'Bar',
'start': {'dateTime': start_datetime.isoformat()},
'end': {'dateTime': (start_datetime + timedelta(minutes=15)).isoformat()},
}).execute()

print(event)

You just have to change <YOUR EMAIL HERE> to your gmail account then, it will reflect to your calendar.

Lastly, you might want to check the document about Handle API Errors, this will be useful on how to handle error responses.

Hope this helps