0
votes

I've created custom model Profile and linked it to the User model which works fine. But, now I want to create custom UserCreateForm in Django admin. I redefined it and added necessary fields, but after that still shows, all fields from profile model, ex: phone, home_address. I need fields displayed as : 'first_name', 'last_name', 'username', 'password1', 'password2' in the UserCreateForm. What have I done wrong?

from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm
from .models import Profile

class NewUserCreateForm(UserCreationForm):

   class Meta:
       fields = ('username', 'first_name', 'last_name',)

class ProfileInline(admin.TabularInline):
    model = Profile

class UserAdmin(UserAdmin):

   add_form = NewUserCreateForm

   add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('first_name', 'last_name', 'username','password1', 'password2', ),
       }),
       )
   inlines = [ProfileInline]

admin.site.unregister(User)
admin.site.register(User, UserAdmin)
1
If you would like to disable some fields from showing try class UserAdmin(admin.ModelAdmin): readonly_fields=('first_name', 'last_name', 'username',) - Panos Angelopoulos
is it necessary to inherit from admin.ModelAdmin? I'm inherit from UserAdmin and indicated fields: phone and home_address in readonly_fields but they are still displayed. These fields I need to hide only in UserCreateForm - Serg Bombermen
If i was in your shows i ll try to take advantage of exclude in my form inside class Meta. So try to change your code exclude : ('phone', 'home_address' , ). - Panos Angelopoulos
I'm add exclude in Meta class form NewUserCreateForm: exclude = ('phone', 'home_address',) and still is show. If I can help, I've added the model User with help OnetoOne - Serg Bombermen
In my code, if I am using this snippet : class ProfileInline(admin.TabularInline): model = Profile readonly_fields = ('phone', 'home_address' ,) it works fine. Did you try it without result ? - Panos Angelopoulos

1 Answers

1
votes

Firstly your models.py file will be :

from django.db import models

from django.contrib.auth.models import User

# Create your models here.

class Profile(models.Model):
    user_id = models.OneToOneField(User, on_delete=models.CASCADE) 
    phone = models.CharField(max_length=100)
    address = models.CharField(max_length=256)

...

Then your admin.py file.

from.models import Profile
# Register your models here.


class ProfileAdmin(admin.ModelAdmin):
    model = Profile
    exclude = ['phone',] # Or whatever you don't want to display.

admin.site.register(Profile, ProfileAdmin)

For extended implementation please add or remove based on your needs.

Hope it helps.