Search code examples
djangodjango-signals

Is the word 'profile' an in build feature in Django?


I am a newbie to Django. Below code is to create a user profile when new user signup for my Blog application.

Doubt : - Why do we use profile instead of Profile in the last code line ? please note the capitalized word 'Profile'

from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile


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


@receiver(post_save, sender=User)
def save_profile(sender, instance, *args,**kwargs):
    instance.profile.save()'''  #last code line


Solution

  • No, it is not a builtin feature. If you define a relation from your model (for example Profile to User), Django automatically creates a reverse relation. You can specify the name of that relation with the related_name attribute.

    You can thus specify the name differently by altering the related_name [Django-doc] of the relation, for example:

    from django.db import models
    from django.contrib.auth import get_user_model
    
    class Profile(models.Model):
        user = models.OneToOneField(
            get_user_model(),
            on_delete=models.CASCADE,
            related_name='other_attribute'
        )

    In that case the name of the profile is:

    from django.contrib.auth import get_user_model
    
    @receiver(post_save, sender=get_user_model())
    def save_profile(sender, instance, *args,**kwargs):
        instance.other_attribute.save()

    By default the related_name value is the name of the class, but in lowercase, and with underscores (_) as word separator.

    This is according to PEP-8 where attributes of a class are written in lowercase and with underscores as word separator.