Hannan
Hannan

Reputation: 1191

Django how to save user info in model came though API

I'm making a webapp which is connected with an API. When user authorizes my webapp to use 3rd party API, the API send information relating to user. I want to save that information in my model to use it for future. I'm not sure how to save that information in the model against the user already logged in. Here is my code:

views.py:

from .models import UserInfo

def auth_finish(request):
    app_session = request.session
    try:
        oa_auth = auth_flow(app_session).finish(request.GET)
        if request.method == 'GET':
            UserInfo.user = request.user # How to save this model?
            UserInfo.access_token = oa_auth.access_token # How to save this model?
            UserInfo.account_id = oa_auth.account_id # How to save this model?
            UserInfo.dbx_user_id = oa_auth.user_id # How to save this model?
        return render(request, 'index.html')
    except oauth.BadRequestException as e:
        return HttpResponse(e)

models.py

from django.contrib.auth.models import User

class UserInfo(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    access_token = models.CharField(max_length=20, blank=False)
    account_id = models.CharField(max_length=10, blank=False)
    dbx_user_id = models.CharField(max_length=10, blank=False)

The information is coming to my views correctly and I'm able to build a dictionary with it in the views.py. How can I save this information?

def auth_finish(request):
    app_session = request.session
    try:
        oa_auth = auth_flow(app_session).finish(request.GET)
            user_auth_info = dict()
            user_auth_info['access_token'] = oa_auth.access_token
            user_auth_info['account_id'] = oa_auth.account_id
            user_auth_info['user_id'] = oa_auth.user_id
            user_auth_info['app_user'] = request.user
            print(user_auth_info)
        return render(request, 'index.html')
    except oauth.BadRequestException as e:
        return HttpResponse(e)

Upvotes: 1

Views: 79

Answers (1)

Laurynas Tamulevičius
Laurynas Tamulevičius

Reputation: 1579

from .models import UserInfo

def auth_finish(request):
    app_session = request.session
    try:
        oa_auth = auth_flow(app_session).finish(request.GET)
        if request.method == 'GET':
            user_info_instance = UserInfo(user=request.user, access_token=oa_auth.access_token, account_id=oa_auth.account_id, dbx_user_id=oa_auth.user_id)
            user_info_instance.save()
        return render(request, 'index.html')
    except oauth.BadRequestException as e:
        return HttpResponse(e)

Upvotes: 1

Related Questions