Home > Back-end >  Model not saving refresh token
Model not saving refresh token

Time:02-14

Just trying to save the refresh token from Google OAuth 2.0 into the abstractuser profile which signed in. It displays the refresh token and the user correctly. However when logged in the user doesn't have the refresh token stored in the model.

pipeline.py:

from .models import Profile
def save_token(user,*args,**kwargs):
    extra_data = user.social_auth.get(provider="google-oauth2").extra_data
    print(extra_data["refresh_token"],user)
    Profile.objects.get_or_create(
        username=user, defaults={"refresh_token": extra_data["refresh_token"]}
    )

models.py

from django.db import models
from django.contrib.auth.models import AbstractUser

class Profile(AbstractUser):
    refresh_token = models.CharField(max_length=255, default="")

 

Now when displaying it, it comes up empty.

calendar.html:

{% block content %}
   
    {{user.refresh_token}}
    
    <h1>Calendar</h1>
    <button> </button>
    <ul>
        {% for result in results %}
            <li>{{result.start.date}}{% if result.end.date %}-{% endif%}{{result.end.date}}: {{result.summary}}</li>
        {% endfor %}
    </ul>
{% endblock %}

CodePudding user response:

The queryset method get_or_create does not update values in the model, it only creates a new object if it doesn't exist. If you're trying to update values in an existing object, you should use the second value that get_or_create returns to confirm it already exists and make the necessary updates.

So the adjustment would look like this:

def save_token(user,*args,**kwargs):
    extra_data = user.social_auth.get(provider="google-oauth2").extra_data

    profile, created = Profile.objects.get_or_create(
        username=user, defaults={"refresh_token": 
        extra_data["refresh_token"]}
    )

    # `created` will be false if the object exists

    if not created:
        profile.refresh_token = extra_data["refresh_token"]
        profile.save()
  • Related