我无法使用Cookiecutter Django框架创建自定义用户字段。我已经大大改变了cookiecutter模板 - 删除django-allauth
但是很多结构保持不变。
如果我想在User模型中添加另一个字段(例如," department" - 用户是员工),我会在哪里添加它?
我想我可以将department
变量添加到users/models.py
,但它似乎无法正常工作。当我登录admin
网站时,添加用户时我看不到department
字段。同样,我在管理网站中看不到name
字段 - 我只看到名字,姓氏和电子邮件地址。
# users/models.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from django.contrib.auth.models import AbstractUser
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class User(AbstractUser):
# First Name and Last Name do not cover name patterns
# around the globe.
name = models.CharField(blank=True, max_length=255)
department = models.CharField(blank=True, max_length=5)
def __str__(self):
return self.username
def get_absolute_url(self):
return reverse('users:detail', kwargs={'username': self.username})
管理员档案:
# users/admin.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as AuthUserAdmin
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
from .models import User
class MyUserChangeForm(UserChangeForm):
class Meta(UserChangeForm.Meta):
model = User
class MyUserCreationForm(UserCreationForm):
error_message = UserCreationForm.error_messages.update({
'duplicate_username': 'This username has already been taken.'
})
class Meta(UserCreationForm.Meta):
model = User
def clean_username(self):
username = self.cleaned_data["username"]
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError(self.error_messages['duplicate_username'])
@admin.register(User)
class UserAdmin(AuthUserAdmin):
form = MyUserChangeForm
add_form = MyUserCreationForm
答案 0 :(得分:1)
您缺少fieldsets属性:
@admin.register(User)
class UserAdmin(AuthUserAdmin):
form = MyUserChangeForm
add_form = MyUserCreationForm
fieldsets = (
('', {'fields': ('department',)}),
) + AuthUserAdmin.fieldsets
list_display = ('username', 'department', 'is_superuser')
search_fields = ['username', 'department']
您无需设置属性list_display
和search_fields
即可显示department
字段。但是我将它们留在了样本中,因为它们在Django
管理员自定义方面非常方便。
的ModelAdmin list_display:
设置list_display以控制更改上显示的字段 管理员的列表页面。
的ModelAdmin search_fields:
设置search_fields以在管理员更改列表中启用搜索框 页。这应该设置为将要的字段名称列表 只要有人在该文本框中提交搜索查询,就会进行搜索。