Python-Django - How to show template only items associated with logged in user

Asked

Viewed 46 times

0

I have a small project that is an "to-do list", or to-do list, done in Python-Django and I will implement a login system as I have done with other projects. However, this time I wanted to show only the lists related to that logged in user, how should I do ? Add something in the views ?

1 answer

0


For a user to be able to see only their items, these items must be marked with the user who actually owns them.

So, your model of ToDo must also contain a foreign key field from the Django user table.

class Item(models.Model):
    ...
    usuario = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)

Settings.AUTH_USER_MODEL contains the table name that Django uses to store users.

Thus, when saving a Whole at the base, you must indicate which user owns this item. The logged-in user is inside the object request, received as a parameter in the view:

def salvarItem(request):
    item.usuario = request.user
    item.save()

And, finally, when listing the only items of the logged-in user, just filter through this field:

def listarItems(request):
   itens = Item.objects.filter(usuario=request.user)
   return render('tela.html', { 'itens': itens})
  • 1

    Thanks for the reply bro, it worked

Browser other questions tagged

You are not signed in. Login or sign up in order to post.