Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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 = ['']
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