Django中add_form与form的区别及Admin注册参数疑问
add_form vs form & Admin Registration Question Great question! Let's break this down clearly so you understand exactly what's going on here.
Difference Between add_form and form
These two attributes in CustomUserAdmin serve distinct purposes in the Django admin workflow:
form = CustomUserChangeForm: This is the form used to edit existing users. When you click on an already-created user in the admin to modify their details (like email, permissions, or custom fields), this form loads. It's designed to work with existing user data—for example, it won't ask for a password confirmation (since the user already has a password), and it includes all fields relevant to updating a user's profile or settings.add_form = CustomUserCreationForm: This is the form used to create new users. When you click the "Add User" button in the admin, this form is displayed. It's optimized for new user setup: it typically includes fields like username/email, password, and password confirmation (to ensure the user enters their password correctly), and it excludes fields that are automatically populated or only relevant to existing users (like last login timestamp or date joined).
Why Register Both CustomUser and CustomUserAdmin?
When you call admin.site.register(CustomUser, CustomUserAdmin), you're telling Django's admin system two critical things:
CustomUser: This is the data model you want to manage in the admin—this is the class that maps to your user database table, holding all the user data.CustomUserAdmin: This is the configuration class that defines how the admin interface should handle yourCustomUsermodel. It controls everything from which forms to use (like theadd_formandformwe just discussed) to which fields show up in the list view, how filters work, and even custom actions.
If you only registered CustomUser without passing CustomUserAdmin, Django would fall back to using the default UserAdmin class (or a generic admin configuration). But since you've created a custom user model, the default UserAdmin won't know about your custom fields or your custom form logic—leading to broken admin functionality. By passing your CustomUserAdmin, you're ensuring Django admin knows exactly how to properly create, edit, and display your custom users.
内容的提问来源于stack exchange,提问作者Nazim Kerimbekov

