Error saving model instance - foreign key on user

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

Are you setting the right variable here?

Should these reference dropbox_user_id and dropbox_account_id?

Hi Ken,

Thanks for the reply.

The value user_id is actually the value returned in the data value which is pulled from a json string. It is the user’s Dropbox User ID after completing the OAUTH2 validation. What I’m trying to do here is to create and/or update the data in the DropboxUser object (dbu) with the information returned from this OAUTH2 call. dbu.user is the foreign key in the DropboxUser model.

Hopefully this explains things, but if not, please let me know.

Thanks,
Bob

So I checked through the debugger and the value of request.user does in fact show the currently logged in user and this is the foreign key in the modle, so I’m not sure why the insert fails.

What I’m pointing out is that there appears to be a mismatch between the names of the fields in the model and the names of the fields that you’re assigning values to in your code.

You have:

But you’re assigning values to:

Wow, yes you are correct. I was staring at that for an hour and didn’t notice.

I think I’m all set. Thanks for the reply.