djangodjango-authenticationdjango-users

One User model for Auth and User Django


I'm using the Django auth feature to create users. I also want to extend the user to add things like profile pictures and other information.

My problem is that I now have to User models to manage. One from Auth and one from the model I created. Can this be consolidated into one model?

from urls.py:

path('accounts/',include('django.contrib.auth.urls'))

from models.py:

class User(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    firstName = models.CharField(max_length=200)
    lastName = models.CharField(max_length=200)
    image= models.ImageField(upload_to='profile_image',default='profile_image/SSMILE.jpg')

from views.py

class SignUp(generic.CreateView):
    form_class = UserCreationForm
    success_url = reverse_lazy('login')
    template_name = 'signup.html'

I have 2 User models

As you can see I have 2 User models. I have to end up creating the auth user through sign up then in my homepage view do this:

if str(request.user) != "AnonymousUser":
    try:
        getuser = User.objects.get(user=request.user)
        print(getuser)
    except User.DoesNotExist:
        newUser= User(user=request.user,firstName=request.user,lastName="change")
        newUser.save()

which is a hack I want to avoid doing.


Solution

  • You are adding another model with same name User. It is already there. If you are extending your user model, then you don't need to add first_name or last_name any more,

    Check this,

    class Profile(models.Model):
       profile_picture = models.ImageField(upload_to=#add your path)
       user = models.OneToOneField(User, on_delete=models.CASCADE)
    
    
    @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()
    

    This will extend your existing user model.