Reputation: 761
I read a part of the doc, and some articles, but my code is not working.
OBS: i'm using custom User created with AbstractUser, but i not add extra fields
Look this example
profile.signals.py:
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth import get_user_model
from .models import Profile
User = get_user_model()
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
now, look in the user creation:
>>> from accounts.models import User
>>> me = User.objects.create(username='myusr', email='[email protected]', password='me123456')
>>> me
<User: myusr>
>>> me.save()
>>> me.profile
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/mnt/sda4/Development/coding/Projects/codesv3/env/lib/python3.7/site-packages/django/db/models/fields/related_descriptors.py", line 415, in__get__
self.related.get_accessor_name()
accounts.models.User.profile.RelatedObjectDoesNotExist: User has no profile.
i dont know what's wrong. Also because I have not used it before and i not know about SQL triggers
Upvotes: 1
Views: 186
Reputation: 559
In your signals.py
file, save profile
after it's created, like below:
@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
instance.profile.save()
Make sure, you import signals
in your related apps.py
file like below example:
from django.apps import AppConfig
class UsersConfig(AppConfig):
name = 'users'
def ready(self):
import users.signals
Then also make sure you have made the below change:
you must add app's config
to either of two files.
In your settings.py
file's INSTALLED_APPS
, like mentioned in this link: Django create profile for user signal.
OR,
In your related app
's __init__.py
file, like this (in this example, the related app is users
): default_app_config = 'users.apps.UsersConfig'
Upvotes: 1
Reputation: 1986
First, this command create user and you do not need to save it after creating:
me = User.objects.create(username='myusr', email='[email protected]', password='me123456')
Second, where your signals places? If you put it in models everything should works. Also you can place where you want but you need to import it in your apps like here:
class ProfileConfig(BaseConfig):
name = ...
def ready():
import profiles.signals # where your signals place
Upvotes: 0