Reputation: 403
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)
Upvotes: 0
Views: 97
Reputation: 609
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.
Upvotes: 1