title: How to pass a user instance in a class-based view
body: <p><br />
  <br />
  I would like to pass the user instance of the current user to a variable in a class-based view and feed it in a second step, within a python script, to a database table column defined as <code>author = models.ForeignKey(User, on_delete=models.PROTECT)</code>. Related to that column I get the following integrity error: <code>NOT NULL constraint failed..</code> From the traceback I can see that my variable <code>loggedUser</code>, which I had attributed <code>self.request.user</code>, is a <code>SimpleLazyObject</code>. <br />
  <br />
  I have found <a href="https://stackoverflow.com/questions/11314905/request-user-returns-a-simplelazyobject-how-do-i-wake-it">another question</a> similar to mine. But it discusses the issue related to functions - I am having difficulties to adapt the answers to my case of a class-based view.
  <br />
  <br />
  How can I pass my user instance?<br />
  Thank you!
  <br /></p>
  
  <h2>models.py</h2>
  
  <pre><code>from django.db import models
  from django.contrib.auth.models import User
  
  class Data(models.Model):
      temperature = models.FloatField(max_length=5)
      author = models.ForeignKey(User, on_delete=models.PROTECT) 
  </code></pre>
  
  <p><br /></p>
  
  <h2>views.py</h2>
  
  <pre><code>from . import apythonscript
  from django.views.generic import TemplateView
  
  class PlotGraphView(TemplateView):
  
      def get_context_data(self, **kwargs):
          loggedUser = self.request.user
          context['plot'] = apythonscript.putDataInDB(loggedUser)
          return context
  </code></pre>
  
  <p><br />      </p>
  
  <h2>apythonscript.py</h2>
  
  <pre><code>from app.models import Data
  
  def putDataInDB(loggedUser):
      mydata=json.loads(response)
  
      for line in mydata['feeds']:
      #    try:
          data_handle = Data(temperature=line['field1'], author=loggedUser,)
          data_handle.save()
      #    except:
      #        continue
  </code></pre>
  
  <h2>traceback</h2>
  
  <p><a href="http://dpaste.com/1EGMFHZ" rel="nofollow noreferrer">link to traceback</a></p>