I have the following model defined…
class DropboxUser(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
auth_token = models.TextField(max_length=255, null=True, blank=True)
refresh_token = models.TextField(max_length=255, null=True, blank=True)
expiration_date = models.DateField(null=True, blank=True)
dropbox_user_id = models.TextField(max_length=100, null=True, blank=True)
dropbox_account_id = models.TextField(max_length=100, null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True)
id = models.UUIDField(primary_key=True,
default=uuid.uuid4, editable=False, unique=True)
def __str__(self):
return str(self.user.username)
In my view, I am attempting to create a new entry for that model. Here is the code…
def dropbox_authorized(request):
code = request.GET['code']
data = requests.post("https://api.dropboxapi.com/oauth2/token",
data={"code": code,
"grant_type": "authorization_code",
"redirect_uri": f"{BASE_URL}/{REDIRECT_URI}",},
auth=(USER_APP_KEY, USER_APP_SECRET))
json_string = data.json()
access_token = json_string["access_token"]
expires_in = json_string["expires_in"]
user_id = json_string["uid"]
account_id = json_string["account_id"]
request.session['access_token'] = access_token
dbu = DropboxUser()
dbu.user = request.user
dbu.access_token = access_token
dbu.user_id = user_id
dbu.account_id = account_id
a = datetime.datetime.now()
dbu.expiration_date = a + datetime.timedelta(0, expires_in)
dbu.save()
On the dbu.save() line I am getting the following error.
(1452, 'Cannot add or update a child row: a foreign key constraint fails (`ursus`.`dropboxui_dropboxuser`, CONSTRAINT `DropboxUI_dropboxuser_user_id_bdf6f76c_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`))')
I am doing a similar operation with another model which also has the current user as a foreign key. I can’t figure out why I am getting the error on this model.
Any help would be greatly appreciated!
Thanks,
Bob