Galil
Galil

Reputation: 869

Django model save() - AttributeError: 'NoneType' object has no attribute 'append'

In my models.py I want to extend the Django User model by adding an email_list.

from django.contrib.postgres.fields import ArrayField

class User(AbstractUser):
    email_list = ArrayField(models.EmailField(max_length=100), null=True, blank=True)
    [...]

This email_list has to have the user email as default value. I found that the best way to do this, is by overriding the save() method:

def save(self, *args, **kwargs):
    self.email_list.append(self.email)
    super(User, self).save(*args, **kwargs)

However, when I add a user I get the following error:

AttributeError: 'NoneType' object has no attribute 'append'

And the print(type(self.email_list)), returns <type 'NoneType'>

What is wrong with the ArrayField?

Upvotes: 2

Views: 1533

Answers (2)

Zakaria Moumen
Zakaria Moumen

Reputation: 1

the initial None value is occurring because null=True, even if default=list. to avoid default value overriding, remove or set null to False

from django.contrib.postgres.fields import ArrayField

class User(AbstractUser):
    email_list = ArrayField(models.EmailField(max_length=100), blank=True, default=list)
[...]

Upvotes: 0

Juan Diego Garcia
Juan Diego Garcia

Reputation: 823

You should use a callabe such as list for the default value.

from django.contrib.postgres.fields import ArrayField

class User(AbstractUser):
    email_list = ArrayField(models.EmailField(max_length=100), null=True, blank=True, default=list)
    [...]

https://docs.djangoproject.com/en/1.11/ref/contrib/postgres/fields/

Upvotes: 1

Related Questions