Costantin
Costantin

Reputation: 2646

Call two function inside a class based view - Django

I have a class connected to a template, inside it I have two functions, one is to authenticate the user (using credentials available in my db) and the second one is to actually get some data and push it to my template. However using print('whatever') I see that neither function gets called when I call the class. Why?

views.py

class GenerateReport(TemplateView): # This view is responsable to access users data and return it
    template_name = 'ga_app/report.html'
    def generate_report(request): # authenticate user
        c = CredentialsModel.objects.get(user_id = request.user.id)
        credentials = c.credentials
        http = httplib2.Http()
        http = credentials.authorize(http)
        service = build('analyticsreporting', 'v4', http=http)
        print('This first function is not called')

    def print_data(request): # Get some data
        profile_id = GoogleProperty.objects.get(user_id = request.user.id)
        some_data = service.data().ga().get(
          ids='ga:' + profile_id,
          start_date='7daysAgo',
          end_date='today',
          metrics='ga:sessions').execute()
        print('This second function neither')
        return render(request, self.report, {'some_data': some_data}, {'profile_id': profile_id})

urls.py

url(r'^re/$', GenerateReport.as_view(), name='re'),

The shell obviously doesn't show anything printed out, and the template doesn't render metrics and/or profile_id

Upvotes: 0

Views: 2365

Answers (1)

NS0
NS0

Reputation: 6096

Those functions will not be called by default, so you need to call them yourself. Looking at the documentation for TemplateView it looks like you would need to implement a get_context_data method, where you can call those functions, and return a context for your template.

Upvotes: 2

Related Questions