Django Foreign Key. How to access child model through the parent

42 Views Asked by At

So I created custom Profile model for a user and it's connected to the base Django User model via Foreign Key. I can easily access User model's fields through my Profile model because the Profile model has the field with Foreign Key to a User model (for example profile.user.username and etc.)

But how do I access Profile model fields via User model?

Here is the Profile Model

    user = models.ForeignKey(User, on_delete=models.CASCADE)
    id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True)
    username = models.CharField(max_length=150)
    email = models.EmailField()
    image = models.ImageField(upload_to='images/user_profiles', blank=True, null=True)

    def __str__(self):
        return f"{self.user}'s profile"

And I've tried to access profile id like that, but it doesn't work

 a href="{% url 'profile' pk=request.user_profile.id %}" ...```
    
    path('profile/<str:pk>/', views.user_profile_view, name='profile'),
1

There are 1 best solutions below

0
Kiarash Gh On

this might help:

 a href="{% url 'profile' pk=request.user.profile.id %}" ...```