Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: field's default value from model instance

I'm trying to get the last_name and first_name of the newly created user and create the foldername using both values.

But I get type object 'User' has no attribute 'first_name'

This is my Users model:

def create_folder_name(first_name, last_name):
    return first_name + last_name


class User(AbstractUser):
    folder_name = models.CharField(max_length=255, unique=True,
                                   default=create_folder_name(User.first_name, User.last_name))

How can I pass the User.first_name to my function

like image 346
Yannick Avatar asked May 20 '14 17:05

Yannick


2 Answers

If your default is constructed from other field values, you need to have a model instance to get the values.

Override the save() method:

class User(AbstractUser):
    folder_name = models.CharField(max_length=255, unique=True)

    def save(self, *args, **kwargs):
        if not self.folder_name:
            self.folder_name = create_folder_name(self.first_name, self.last_name)
        super(User, self).save(*args, **kwargs)
like image 51
alecxe Avatar answered Sep 18 '22 00:09

alecxe


I think you're better off overriding the save method in your User model:

class User(AbstractUser):
    folder_name = models.CharField(max_length=255, unique=True)

    def save(self, *args, **kwargs):
        self.folder_name = create_folder_name(self.first_name, self.last_name)
        super(User, self).save(*args, **kwargs)
like image 40
J. Ghyllebert Avatar answered Sep 22 '22 00:09

J. Ghyllebert