Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bacalj/0c5be236080801a4677ffe8d8e0f0c97 to your computer and use it in GitHub Desktop.
Save bacalj/0c5be236080801a4677ffe8d8e0f0c97 to your computer and use it in GitHub Desktop.
Using Gspread in Django View To Access Google Sheets Data
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from .models import Student
class StudentDetailView(DetailView):
model = Student
template_name = 'student_detail.html'
def get_context_data(self, *args, **kwargs):
# gain access to local fields data to get a key to pass to sheet
myfields = self.object.get_fields()
cskey = myfields[3][1]
# connect and authenticate to google sheets service
gscope = ['https://spreadsheets.google.com/feeds']
gcreds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', gscope)
gclient = gspread.authorize(gcreds)
# get your sheet and pull in all the data
sheet = gclient.open_by_key('-- google sheet id here --').sheet1
enchilada = sheet.get_all_records()
# get the row of the student we are interested in
rowdict = next(item for item in enchilada if item["googleID"] == cskey)
# rebuild context and include data gained from sheet
context = super(StudentDetailView, self).get_context_data(**kwargs)
# this is now value we loop over in template to get everything, blank or not
context['studentmeta'] = rowdict
# but we can also see if we have key/vals and use them in template more purposefully
scratchname = rowdict.get('scratch_username')
if len(scratchname) > 0:
context['scratchname'] = scratchname
# et voila, rest of looping happens in template
return context
# In the template:
# Scratch Name: {{ scratchname }}
# loop over other columns not explicity pulled out
# {% for key, value in studentmeta.items %}
# <li>{{ key }}:{{ value }}</li>
# {% endfor %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment