Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Connect Google Calendar to Django Application
Karanjot Singh
Karanjot Singh

Posted on • Edited on • Originally published atMedium

     

Connect Google Calendar to Django Application

A Step-by-Step Guide to Seamlessly Integrate Google Calendar with Your Django Application for Enhanced Scheduling and Event Management.

Integrating Google Calendar with your Django application can significantly enhance your web app’s functionality by enabling scheduling, event management, and calendar synchronization. This guide will walk you through the steps to connect Google Calendar to your Django application, covering everything from setting up Google API credentials to implementing the necessary code in Django.

Prerequisites

Before you start, ensure you have the following:

1. Django Application: A working Django application.

2. Google API Console Account: Access to the Google Cloud Console.

3. Google Calendar API Enabled: The Google Calendar API should be enabled for your project in the Google Cloud Console.


Step 1: Set Up Google Cloud Project

1. Create a Project:
Go to theGoogle Cloud Console and create a new project.

2. Enable Google Calendar API:
Navigate to the “API & Services” > “Library” and search for “Google Calendar API.” Enable it for your project.

3. Configure Consent Screen:

  • Navigate to the “API & Services” > “OAuth consent screen” and configure the Consent screen.
  • Now select the type of OAuth you want (External in this case as the application would be accessible to anyone having a Google Account).
  • Set all the data for the consent screen like the App Name, logo, support email etc. as required.
  • Click on “Add or remove scopes” and add the following scopes,…/auth/userinfo.email ,…/auth/userinfo.profile,openid to access user information and all the Google Calendar API scopes to access the Google calendar of user. Then click Update to save.
  • Next Add test users. Since our application is not yet verified by google hence only the users in this list would be able to register to this google project. So add all the test emails you would be using to test the google calendar integration.Once done continue to create credentials.

4. Create OAuth Credentials:
Go to “API & Services” > “Credentials” and create credentials. Select OAuth client ID as the type of credentials. Set Web application as the Application type and fill the application details.

  • Authorized redirect URIs: Add the redirect URL for your Django application (e.g.,http://localhost:8000/oauth2callback for local development).

5. Download JSON Credentials:
Download the OAuth 2.0 credentials JSON file and keep it safe. This file contains your client_id, client_secret, and other important information.


Step 2: Install Required Python Packages

You’ll need a few Python packages to interact with Google APIs:

pipinstallgoogle-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client
Enter fullscreen modeExit fullscreen mode

Step 3: Configure Django Settings

Update yoursettings.py with the following:

importos# Google Calendar APIGOOGLE_CLIENT_SECRETS_FILE=os.path.join(BASE_DIR,'path/to/client_secret.json')GOOGLE_API_SCOPES=['https://www.googleapis.com/auth/calendar']REDIRECT_URI='http://localhost:8000/oauth2callback'# Or your production URL
Enter fullscreen modeExit fullscreen mode

Step 4: Create OAuth2 Flow

Create a view to handle the OAuth2 flow:

fromgoogle.oauth2.credentialsimportCredentialsfromgoogle_auth_oauthlib.flowimportFlowfromdjango.shortcutsimportredirectfromdjango.httpimportHttpResponsefromdjango.confimportsettingsdefgoogle_calendar_init(request):flow=Flow.from_client_secrets_file(settings.GOOGLE_CLIENT_SECRETS_FILE,scopes=settings.GOOGLE_API_SCOPES,redirect_uri=settings.REDIRECT_URI)authorization_url,state=flow.authorization_url(access_type='offline',include_granted_scopes='true')request.session['state']=statereturnredirect(authorization_url)defgoogle_calendar_redirect(request):state=request.session['state']flow=Flow.from_client_secrets_file(settings.GOOGLE_CLIENT_SECRETS_FILE,scopes=settings.GOOGLE_API_SCOPES,state=state,redirect_uri=settings.REDIRECT_URI)flow.fetch_token(authorization_response=request.build_absolute_uri())credentials=flow.credentialsrequest.session['credentials']=credentials_to_dict(credentials)returnHttpResponse('Calendar integration complete. You can now use Google Calendar with your Django app.')defcredentials_to_dict(credentials):return{'token':credentials.token,'refresh_token':credentials.refresh_token,'token_uri':credentials.token_uri,'client_id':credentials.client_id,'client_secret':credentials.client_secret,'scopes':credentials.scopes}
Enter fullscreen modeExit fullscreen mode

Step 5: Handle Google Calendar API Requests

Once the OAuth2 flow is completed, you can make authenticated requests to Google Calendar API. Here’s a simple example to list the user’s calendar events:

fromgoogleapiclient.discoveryimportbuilddeflist_events(request):credentials=Credentials(**request.session['credentials'])service=build('calendar','v3',credentials=credentials)events_result=service.events().list(calendarId='primary',maxResults=10).execute()events=events_result.get('items',[])returnHttpResponse(events)
Enter fullscreen modeExit fullscreen mode

Step 6: Update URLs

Add the URLs for the views in yoururls.py:

fromdjango.urlsimportpathfrom.importviewsurlpatterns=[path('google-calendar/init/',views.google_calendar_init,name='google_calendar_init'),path('oauth2callback/',views.google_calendar_redirect,name='google_calendar_redirect'),path('google-calendar/events/',views.list_events,name='list_events'),]
Enter fullscreen modeExit fullscreen mode

Step 7: Run and Test

  1. Start Your Django Server:
    Run your Django development server usingpython manage.py runserver.

  2. Authenticate:
    Navigate to/google-calendar/init/ in your browser. You’ll be redirected to Google’s OAuth2 consent page.

  3. Access Events:
    After authentication, go to/google-calendar/events/ to view your Google Calendar events.

Conclusion

Integrating Google Calendar with your Django application allows you to build powerful scheduling features directly within your app. By following this guide, you’ve set up OAuth2 authentication, connected to the Google Calendar API, and fetched calendar events. You can now expand this integration to include event creation, updates, and other calendar management features as needed.

PS: Remember to handle the credentials securely and ensure proper error handling for a robust application.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I'm a developer, student and a tech enthusiast. I love creating awesome projects. I believe that one's knowledge increases by sharing it.
  • Location
    New Delhi, India
  • Work
    Student
  • Joined

More fromKaranjot Singh

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp