0

I've successfully logged in my facebook account using Social-Auth-App-Django. Now I need to get my user ID so that I can filter the database using the user's ID but I don't have any idea how to do it. In django template it looks like this {{ user.id }} but I don't know how to get it in views.py

Here's my template code for login into facebook

    <a href="{% url 'social:begin' 'facebook' %}" class='btn'>
         <img src="/static/img/facebook.png" alt="">
         Login with Facebook
    </a>

And here's my code in views.py

    @login_required
    def home(request):
         items = Products.objects.filter(product_owner__id=user_id)
         return render(request, 'seller.html', {
             "items": items
    })

user_id is what I actually need.

Thanks in advance!

markwalker_
  • 12,078
  • 7
  • 62
  • 99
Danilo
  • 11
  • 1

1 Answers1

1

The way you do that would be;

@login_required
def home(request):
    items = Products.objects.filter(product_owner=request.user)
    return render(
        request,
        'seller.html',
        {
            "items": items
        }
    )

If you didn't have the login_required decorator this wouldn't work however. In that case you'd have to check that they're authenticated.

That scenario would look more like;

def home(request):
    if request.user.is_authenticated:
        items = Products.objects.filter(product_owner=request.user)
    else:
        items = Products.objects.none()

    return render(
        request,
        'seller.html',
        {
            "items": items
        }
    )

Docs relating to this can be found here; https://docs.djangoproject.com/en/3.0/topics/auth/default/#authentication-in-web-requests

markwalker_
  • 12,078
  • 7
  • 62
  • 99