Search code examples
pythondjangodjango-authenticationdjango-profiles

How the datas are connected to the specific user ID?


I'm new to Django and python. I've done login forms but I need to know. How can I connect the contents of the page with the user. For example: It's a Q&A site. When you logged in, It shows profile page with the questions that user asked before. How the datas are linked to the specific user ID in the model? Can it be done using the User object? If so, could you give me some simple example with the script?

Thank you.


Solution

  • Anything that "belongs" to a user, should either have a ForeignKey or ManyToManyField (depending on whether the object is owned by one user or many) to User on it. Then you can either filter the model based on the User:

    SomeModel.objects.filter(user=some_user)
    # where `user` is the name of your foreign key field
    

    Or you can access the model through the user via reverse relations, for example:

    class SomeModel(models.Model):
        ...
        user = models.ForeignKey(User)
    
    # Later ...
    
    some_user.somemodel_set.all()
    

    The second method is more typical since you generally have the user already from the request, so in your view, you'd just do:

    somemodels = request.user.somemodel_set.all()
    

    To get all the SomeModels that belong to the currently logged-in user.