Django how to link Users to Usermodel

Viewed 84

Hello I am pretty new to Django and don't get yet fundamental ideas of Users. I was able to create a registration page to create users which are shown on the admin page in the "Authentication and AUthorization -> Users".

Now I want the users to logg in and create their profiles. They should add some additional information like name, bio, picture etc. Every user should be able to add and see its own profile.

To do that I created a model:

    class Profile(models.Model):
        firstname = models.CharField(max_length=50)
        lastname = models.CharField(max_length=50)
        bio = models.TextField()
        profile_pic = models.ImageField(upload_to="images/")
        def __str__(self):
            return self.firstname + ' | ' + self.lastname

In my view and the html I am able to add these informations to the model. But HOW exactly can I relate this "Profile"-Model to the individual user? What do I miss here?

2 Answers

You can do this via adding a OneToOneField relationship between Profile and the default User:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    firstname = models.CharField(max_length=50)
    lastname = models.CharField(max_length=50)
    bio = models.TextField()
    profile_pic = models.ImageField(upload_to="images/")
    def __str__(self):
        return self.firstname + ' | ' + self.lastname

You can make a OneToOneField to the AUTH_USER_MODEL setting [Django-doc]. This settings contains a string with the qualified name of the user model. This is better than linking to the User model of django.contrib.auth.models.User, because if you later create a custom user model, the references to that user model will be updated:

from django.conf import settings

class Profile(models.Model):
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE
    )
    # …

For more information, see the referencing the user model section of the Django documentation.

Related