Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove/hiding username field in django admin edit user form

The frontend user signup form doesn't have username field as I am using email to login.Now I have access to django admin.

When I edit an user I get that username field to edit but I do not want that field to be editable or view-able at all.

admin.py --

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from .models import UserProfile

class ProfileInline(admin.StackedInline):
    model = UserProfile
    can_delete = False
    verbose_name_plural = 'Profile'
    fk_name = 'user'

class CustomUserAdmin(UserAdmin):
    inlines = (ProfileInline, )
    list_display = ('email', 'first_name', 'last_name', 'is_staff')
    list_select_related = ('profile', )

    exclude = ('username',)

    def get_inline_instances(self, request, obj=None):
        if not obj:
            return list()
        return super(CustomUserAdmin, self).get_inline_instances(request, obj)


admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)

forms.py --

from django import forms
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div, Field
from ajax_select.fields import AutoCompleteSelectField, AutoCompleteField
from phonenumber_field.formfields  import PhoneNumberField
from . import models
from captcha.fields import ReCaptchaField


class SignUpForm(forms.Form):
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    phone_number = PhoneNumberField(label=_("Phone (Please state your country code eg. +44)"))
    organisation = forms.CharField(max_length=50)
    email = forms.EmailField()
    password1 = forms.CharField(max_length=20)
    password2 = forms.CharField(max_length=20)
    captcha = ReCaptchaField(attrs={'theme' : 'clean'})

models.py--

from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from easy_thumbnails.fields import ThumbnailerImageField
from ciasroot.settings import THUMBNAILER_SIZES, UPLOAD_PATH
from ciasroot.constants import GENDERS, LANGUAGES
from ciasroot.util import HashedPk
from phonenumber_field.modelfields import PhoneNumberField
import math, decimal, datetime, os


class UserProfile(models.Model, HashedPk):
    user = models.OneToOneField(User, unique=True, related_name ='profile')
 job_title = models.CharField(max_length=128, blank=True, null=False, default="")
    website = models.URLField(max_length=255, blank=True, null=True)
    organisation = models.CharField(max_length=50, blank=True, null=True, default="")
    phone_number = PhoneNumberField( blank=True, null=True)

The django version is 1.10 so I used exclude. But it throws an error--

KeyError: "Key 'username' not found in 'UserForm'. Choices are: date_joined, email, first_name, groups, is_active, is_staff, is_superuser, last_login, last_name, password, user_permissions."

Do I need to override the signup form because when adding a new user from admin I don't get the fields as frontend signup form(At some point I need to do that as well).

Any help is highly appreciated.

like image 945
Prithviraj Mitra Avatar asked Aug 10 '17 11:08

Prithviraj Mitra


1 Answers

A discussion about this problem is here.

Briefly:

That's because the stock UserAdmin defines fieldsets in which 'username' is a field, you need to modify the fieldsets, too.

For example:

class CustomUserAdmin(UserAdmin):
    # ...
    exclude = ('username',)
    fieldsets = (
        ('Personal info', {'fields': ('full_name', 'email', 'password')}),
        ('Important dates', {'fields': ('last_login', 'date_joined')}),
        ('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}),
    )
like image 158
Anton Shurashov Avatar answered Nov 11 '22 23:11

Anton Shurashov