Abdul Rehman
Abdul Rehman

Reputation: 5664

Django Default value for a custom user field is not added into the db tables

I'm working on a project using Python93.7 & Django(2.2) in which I have extended the user model to add a custom filed for the user. I have defined a default value for that field in the model but when I leave it empty on the form sibmission the default is not added into the DB.

Here's my model: From models.py:

class CustomUser(User):
    team = models.CharField(max_length=255, default='NotInGroup', blank=True)

Here's my view: From views.py:

if form.is_valid():
    print('form is valid')
    print(form.cleaned_data['team'])
    if not form.cleaned_data['team'] == '':
         form.team = form.cleaned_data['team']
     else:
         form.team = 'Default'
    print(form.team)
    user = form.save()

If I leave it empty for form.team it prints out the Default but not saved in DB. Here's my form: From forms.py:

class CustomUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm):
        model = CustomUser
        fields = ('first_name', 'last_name', 'email', 'username', 'team', 'password1', 'password2')

Upvotes: 0

Views: 424

Answers (1)

suhailvs
suhailvs

Reputation: 21710

To extend a User model you have to use AbstractUser class, ie:

from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
    team = models.CharField(max_length=255, default='NotInGroup', blank=True)

now in settings.py add AUTH_USER_MODEL:

AUTH_USER_MODEL = 'myapp.CustomUser'

Upvotes: 1

Related Questions