Extending the User model with custom fields in Django

后端 未结 13 1431
别那么骄傲
别那么骄傲 2020-11-21 23:28

What\'s the best way to extend the User model (bundled with Django\'s authentication app) with custom fields? I would also possibly like to use the email as the username (fo

13条回答
  •  一生所求
    2020-11-22 00:02

    It's too late, but my answer is for those who search for a solution with a recent version of Django.

    models.py:

    from django.db import models
    from django.contrib.auth.models import User
    from django.db.models.signals import post_save
    from django.dispatch import receiver
    
    
    class Profile(models.Model):
        user = models.OneToOneField(User, on_delete=models.CASCADE)
        extra_Field_1 = models.CharField(max_length=25, blank=True)
        extra_Field_2 = models.CharField(max_length=25, blank=True)
    
    
    @receiver(post_save, sender=User)
    def create_user_profile(sender, instance, created, **kwargs):
        if created:
            Profile.objects.create(user=instance)
    
    @receiver(post_save, sender=User)
    def save_user_profile(sender, instance, **kwargs):
        instance.profile.save()
    

    you can use it in templates like this:

    {{ user.get_full_name }}

    • Username: {{ user.username }}
    • Location: {{ user.profile.extra_Field_1 }}
    • Birth Date: {{ user.profile.extra_Field_2 }}

    and in views.py like this:

    def update_profile(request, user_id):
        user = User.objects.get(pk=user_id)
        user.profile.extra_Field_1 = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit...'
        user.save()
    

提交回复
热议问题