Skip to content Skip to sidebar Skip to footer

How To Link Two Tables In Django?

I use the built-in User model in django, but i want use some custom fields, i was create new model class Profile(models.Model): user = models.OneToOneField(User) profile_i

Solution 1:

To create a new Profile object when a new user is created, you can use a pre_save receiver:

from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=User)defcreate_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(
            user=instance
        )

The created parameter is to check if the object has been created ( created=True ) or updated ( created=False )

Solution 2:

I am not sure to understand what you want... If you want to manage profile in admin app you have to register it.

from django.contrib import admin
from myproject.myapp.models import Profile

classProfileAdmin(admin.ModelAdmin):
    pass
admin.site.register(Profile, ProfileAdmin)

Edit: you can use a signal to automatically create a profile when creating a user.

from django.contrib.auth.models import User
from django.db.models.signals import post_save

from myproject.myapp.models import Profile

@receiver(post_save, sender=User)defcreate_profile(sender, instance **kwargs):
    Profile.objects.create(user=instance)

Note that sometime using signals may be hard to maintain. You can also use AbstractBaseUser. This is a classical issue, which is widely covered in a lot of posts. One I particularly like: https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html

Post a Comment for "How To Link Two Tables In Django?"