Sandeep Prasad Kushwaha
Sandeep Prasad Kushwaha

Reputation: 1308

Auto add user firstname in author field in django with custom User model

I created Custom User model in django using below code

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    username = models.CharField(_("Username"), max_length=50, unique=True)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    date_joined = models.DateTimeField(default=timezone.now)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username', ]

    objects = CustomUserManager()

    def __str__(self):
        return self.email

And I also created another model for user profiles like below.

class UserProfile(models.Model):
    user = models.OneToOneField(User, verbose_name=_("User"), on_delete=models.CASCADE)
    first_name = models.CharField(_("First name"), max_length=50)
    middle_name = models.CharField(_("Middle name"), max_length=50, blank=True, null=True)
    last_name = models.CharField(_("Last name"), max_length=50)
    dob = models.DateField(_("D.O.B"), auto_now=False, auto_now_add=False, blank=False, null=False)
    profile_image = models.ImageField(_("Profile picture"), upload_to='user/profile/', blank=True)
    webiste_link = models.URLField(_("Websites"), max_length=200, null=True, blank=True)

At last I created another model for Category like below.

class Category(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_(
        "Author"), on_delete=models.CASCADE, related_name='blog_category')
    title = models.CharField(_("Title"), max_length=50)

I want to auto save logged in user full name instead of user email address. By the way i used below code to auto save logged in user. It works but It only save user email address. But I want user full name instead of email or username.

    obj.author = request.user
    super().save_model(request, obj, form, change)

Upvotes: 2

Views: 1163

Answers (2)

PRMoureu
PRMoureu

Reputation: 13337

You could define a method in the UserProfile model to build this fullname, as you may need it in another function :

class UserProfile(models.Model):
    user = models.OneToOneField(User, verbose_name=_("User"), on_delete=models.CASCADE)
    [...]

    def get_fullname(self):
        return ' '.join([name for name in [
                      self.first_name, 
                      self.middle_name, 
                      self.last_name
                      ] if name])

So you keep this way to save the user foreignkey in a Category:

obj.author = request.user

And later, to call the fullname on a category instance you can use :

# cat = Category.objects.first() 
cat.author.userprofile.get_fullname()

Upvotes: 1

Gilbish Kosma
Gilbish Kosma

Reputation: 887

You can add a filed called full_name in UserProfile model

Class UserProfile(models.Model):
     user = models.OneToOneField(User, verbose_name=_("User"), on_delete=models.CASCADE)
     first_name = models.CharField(_("First name"), max_length=50)
     full_name = mdoels.CharField(_("Full name"),max_length=100)
     middle_name = models.CharField(_("Middle name"), max_length=50, blank=True, null=True)
     last_name = models.CharField(_("Last name"), max_length=50)
     dob = models.DateField(_("D.O.B"), auto_now=False, auto_now_add=False, blank=False, null=False)
     profile_image = models.ImageField(_("Profile picture"), upload_to='user/profile/', blank=True)
     webiste_link = models.URLField(_("Websites"), max_length=200, null=True, blank=True)

     def save(self,*args,**kwargs):
          if not self.full_name:
              self.full_name = self.first_name + " " + self.middle_name + " " + self.last_name
          super().save(*args, **kwargs)

And then using author you can call the users full_name

Upvotes: 0

Related Questions