[英]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.我正在使用
Python93.7
和Django(2.2)
开发一个项目,其中我扩展了用户模型为用户添加了自定义文件。 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.我在模型中为该字段定义了一个默认值,但是当我在表单 sibmission 上将它留空时,默认值不会添加到数据库中。
Here's my model: From models.py
:这是我的模型:来自
models.py
:
class CustomUser(User):
team = models.CharField(max_length=255, default='NotInGroup', blank=True)
Here's my view: From views.py
:这是我的观点:来自
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.如果我将
form.team
留空,它会打印出Default
但不会保存在数据库中。 Here's my form: From forms.py
:这是我的表格:来自
forms.py
:
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = CustomUser
fields = ('first_name', 'last_name', 'email', 'username', 'team', 'password1', 'password2')
To extend a User
model you have to use AbstractUser
class, ie:要扩展
User
模型,您必须使用AbstractUser
类,即:
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
:现在在
settings.py
添加AUTH_USER_MODEL
:
AUTH_USER_MODEL = 'myapp.CustomUser'
Have you tried this? 你有尝试过吗?
if form.is_valid():
user = form.save(
commit=False)
# this will not create a entry in DB
if not form.cleaned_data['team']: user.team = 'Default' user.save() # this will create a entry in DB
Apart from that, If you are trying to extend the Django Auth User model , You should've inherit the AbstractUser
class instead of User
class 除此之外,如果您要扩展Django Auth User模型 ,则应该继承
AbstractUser
类而不是User
类
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.