I am trying to create userprofile after user has been registered in django app.
User creation is working fine but it is not profile models in admin page.
It is not showing any errors.
So far I have done this.
users/signals.py
from django.db.models.signals import post_save
from django.contrib.auth.models import User
#reciever
from django.dispatch import receiver
from .models import Profile
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
instance.profile.save()
users/app.py
from django.apps import AppConfig
class UsersConfig(AppConfig):
name = 'users'
def ready(self):
import users.signals
users/models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pic')
def __str__(self):
return f'{self.user.username} Profile'
Add this line of code to your app's __init__.py
file as @Mohit Harshan mentioned
default_app_config = 'my_app.apps.MyAppConfig'
Why RelatedObjectDoesNotExist
error?
Some of your User
object has no active relation with Profile
instance.So run the following code in your Django shell
users_without_profile = User.objects.filter(profile__isnull=True)
for user in users_without_profile:
Profile.objects.create(user=user)
In your settings.py you should change installed apps
if your settings like this
INSTALLED_APPS = ['users']
you should change it below like this.
INSTALLED_APPS = ['users.apps.UsersConfig']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.