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 author = models.ForeignKey(User, on_delete=models.PROTECT)
. Related to that column I get the following integrity error: NOT NULL constraint failed..
From the traceback I can see that my variable loggedUser
, which I had attributed self.request.user
, is a SimpleLazyObject
.
I have found another question 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.
How can I pass my user instance?
Thank you!
models.py
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)
views.py
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
apythonscript.py
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