[英]Django Admin doesn't recognise blank=True in model
When I try to edit a user (using a custom UserChangeForm) in the Django admin panel, validation insists that fields I have set blank=True
in the model are required.当我尝试在 Django 管理面板中编辑用户(使用自定义 UserChangeForm)时,验证坚持要求我在模型中设置
blank=True
的字段。
I don't know where to begin solving this;我不知道从哪里开始解决这个问题; I had the same issue with the
CustomUserCreationForm
but reverted to using the default which works as expected (asks for username
, password1
& password2
, creates the user with blank display_name
, bio
and profile_picture
fields).我在使用
CustomUserCreationForm
时遇到了同样的问题,但恢复为使用按预期工作的默认设置(要求输入username
、 password1
和password2
,创建具有空白display_name
、 bio
和profile_picture
字段的用户)。
models.py:模型.py:
from django.db import models
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
display_name = models.CharField(max_length=30, blank=True, null=True)
bio = models.TextField(blank=True, null=True)
profile_picture = models.ImageField(upload_to='images/', blank=True, null=True)
def save(self, *args, **kwargs):
if not self.display_name:
self.display_name = self.username
super().save(*args, **kwargs)
def __str__(self):
return self.username
forms.py:表格.py:
from django import forms
from django.contrib.auth.forms import UserChangeForm
from .models import CustomUser
class CustomUserChangeForm(UserChangeForm):
display_name = forms.CharField(label="display_name")
bio = forms.CharField(widget=forms.Textarea)
profile_picture = forms.ImageField(label="profile_picture")
class Meta():
model = CustomUser
fields = ("username", "email", "display_name", "bio", "profile_picture")
admin.py:管理员.py:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .forms import CustomUserChangeForm
from .models import CustomUser
class CustomUserAdmin(UserAdmin):
form = CustomUserChangeForm
fieldsets = (
(None,
{'fields': ('username', 'password', 'email', 'display_name', 'bio', 'profile_picture')}
),
)
model = CustomUser
list_display = ["username", "email",]
admin.site.register(CustomUser, CustomUserAdmin)
From the Django documentation :来自 Django 文档:
By default, each Field class assumes the value is required, so if you pass an empty value – either None or the empty string ("") – then clean() will raise a ValidationError exception:
默认情况下,每个 Field 类都假定该值是必需的,因此如果您传递一个空值——None 或空字符串 ("") - 那么 clean() 将引发 ValidationError 异常:
So you have to add required=False
in your forms.py
.所以你必须在你的
forms.py
中添加required=False
。 For example:例如:
display_name = forms.CharField(required=False, label="display_name")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.