Search code examples
djangomodels

Django - Models - Custom User who Inherites from built-in User


I created CustomUser class and CustomUser has a foreign key to the built-in User class:

class CustomUser(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    website = models.URLField(blank=True)

def __str__(self):
    return self.user.username

In .html (template) I wish to call the website variable, like: {{user.website}}. Unfortunately it doesn't work, but {{user}} and {{user.username}} works.

Another issue is that I want to have relationship with Post by User, so inside template .html I want to show specific user and his all posts

I built already Post model, but I don't know how to call to specific user's posts. I am sure if you can explain how to call to "website", I will do the same to post/user.


Solution

  • Since you are using the one-to-one (profile) method for extending the user class, you have to specify the profile class, such as:

    {{ user.customuser.website }}
    

    See the documentation on various ways to extend the User model.