46π
β
The most common way to accomplish this is to use the Django signals system. You can attach a signal handler (just a function somewhere) to the post_save signal for the User model, and create your favorites list inside of that callback.
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
@receiver(post_save, sender=User)
def create_favorites(sender, instance, created, **kwargs):
if created:
Favorites.objects.create(user=instance)
The above was adapted from the Django signals docs. Be sure to read the signals docs entirely because there are a few issues that can snag you such as where your signal handler code should live and how to avoid duplicate handlers.
π€shadfc
8π
An excellent django-annoying plugin solves this for you with AutoOneToOneField
. Iβm using it for user profiles in all django projects I work on.
- [Django]-Unit testing with django-celery?
- [Django]-How to limit file types on file uploads for ModelForms with FileFields?
- [Django]-How to traverse a GenericForeignKey in Django?
5π
One way would be to register a post_save signal with next handler:
def user_save(sender, instance, created, **kwargs):
if created:
FavouriteList.objects.get_or_create(user=instance)
- [Django]-Django: Grab a set of objects from ID list (and sort by timestamp)
- [Django]-Default value for user ForeignKey with Django admin
- [Django]-Setting expiration time to django password reset token
1π
You can override save method of User model.
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
is_new = self.pk is None # check if object is new to be saved
super().save(force_insert, force_update, using, update_fields)
FavouriteList.objects.create(user=self) if is_new else None
π€Ali Shekari
- [Django]-How do i pass GET parameters using django urlresolvers reverse
- [Django]-Manage.py runserver
- [Django]-Getting 'DatabaseOperations' object has no attribute 'geo_db_type' error when doing a syncdb
Source:stackexchange.com