简体   繁体   中英

Adding fields to custom User model with Cookiecutter Django

I am having difficulty creating custom User fields using the Cookiecutter Django framework. I have changed the cookiecutter template significantly - removing django-allauth but a lot of the structure remains the same.

If I wanted to add another field to the User model (for example, "department" - the users are employees), where would I add it?

I figured I could add a department variable to users/models.py but it doesn't seem to work. When I login to the admin site, I don't see a department field when I add a user. Similarly, I don't see a name field in the admin site - I only see First Name, Last Name, and Email Address.

# 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})

The admin file:

# 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

You are missing the fieldsets attribute:

@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']

You don't need to set the attributes list_display and search_fields to display your department field. But I left them in the sample since they are very handy when it comes to Django admin customization.

ModelAdmin. list_display :

Set list_display to control which fields are displayed on the change list page of the admin.

ModelAdmin. search_fields :

Set search_fields to enable a search box on the admin change list page. This should be set to a list of field names that will be searched whenever somebody submits a search query in that text box.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM