Akshay
Akshay

Reputation: 2785

Updating User model and saving new model - Django

I am trying to save a model by using User model as a ForeignKey, but when I try to save the model I get a RecursionError: maximum recursion depth exceeded.

My code is:

from django.db import models
from django.contrib.auth.models import (User, Group)
from phonenumber_field.modelfields import PhoneNumberField
class AuthenticatorModel(models.Model):
    id = models.IntegerField(auto_created=True, default=1, primary_key=True, serialize=False)
    user_id = models.ForeignKey(User, related_name='auth_user', null=True)
    first_name = models.CharField(default='First Name', max_length=50)
    last_name = models.CharField(default='Last Name', max_length=50)
    phone_number = PhoneNumberField()
    email_id = models.CharField(default='email ID', help_text='Enter the email ID used to register the Django user',
                                max_length=50)

    def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
        try:
            obj = User.objects.get(id=self.id)
            obj2 = AuthenticatorModel.objects.get_or_create(id=self.id)
        except User.DoesNotExist:
            return

        obj.first_name = self.first_name
        obj.last_name = self.last_name
        obj2.phone_number = self.phone_number
        obj.email = self.email_id

        obj.save()
        return super(AuthenticatorModel, self).save()

I am not sure whats wrong in this. How would I create content for AuthenticatorModel and update first_name, last_name and email?

Upvotes: 0

Views: 34

Answers (1)

dentemm
dentemm

Reputation: 6379

You are manually calling get_or_create() in the save() method, but get_or_create() itself is also calling save(). There is no need to create obj2, since you are calling the super method at the end.

You could just do this:

def save(...):
    try:
        obj = User.objects.get(id=self.id)
   except User.DoesNotExist:
        return

    obj.first_name = self.first_name
    obj.last_name = self.last_name
    obj.email = self.email_id
    obj.save()

    return super(AuthenticatorModel, self).save()

Upvotes: 2

Related Questions