0
votes

I'm creating a Custom User Model, based on AbstractUser, which has several extra fields added. I've read through the documentation and assorted examples, but I'm having a couple of frustrating (and probably simple) issues

I'm adding some extra fields to the user and the admin, for later group validation. I'm trying to add the custom fields to the Custom UserCreationForm and UserChangeForm, and I'm using Class Meta: to try and add my new fields in while including the existing ones using the form class CustomUserCreationForm(UserCreationForm):

    class Meta(UserCreationForm):
            model = CustomUser
            fields = UserCreationForm.Meta.fields + ('character_name' ,'ritual_points', 'contribute_points',)

class CustomUserChangeForm(UserChangeForm):

    class Meta(UserChangeForm):
            model = CustomUser
            fields = UserChangeForm.Meta.fields + ('character_name', 'ritual_points', 'contribute_points',)

Which according to all the examples I've seen should just work. However, every time i try and make the migrations, it throws a strop

TypeError: Can't convert 'tuple' object to str implicitly

Everything I've read suggests this should work without any issues.

EDIT The plot thickens. I applied an earlier answer to change the () to a list [] to convert he fields to list, and it came back with a different answer:

TypeError: Can't convert 'list' object to str implicitly

Interestingly, this is working without any problems for the CustomUserCreationForm (which gives a different error if I try and change the () to [], but CustomUserChangeForm is throwing the error.

2

2 Answers

2
votes

just convert fields to list instead of tuple. This will solve your problem.

fields = UserChangeForm.Meta.fields + ['character_name', 'ritual_points', 'contribute_points',]

0
votes

The problem is the UserChangeForm.Meta.fields holds the value '__all__' while UserCreationForm.Meta.fields is in fact a tuple.

>>> from django.contrib.auth.forms import UserCreationForm, UserChangeForm
>>> UserChangeForm.Meta.fields
'__all__'
>>> UserCreationForm.Meta.fields
('username',)

In the documentation it's mentioned that we also need to set the values of fieldsetsand add_fieldsets. See the note at the bottom of this paragraph in the documentation.

I solved the issues you are facing by only extending the creation form and setting the values of fieldsetsand add_fieldsets like so:

class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    model = User
    fieldsets = UserAdmin.fieldsets + (
        (None, {'fields': ('extra_fields',)}),
    )
    add_fieldsets = UserAdmin.add_fieldsets + (
        (None, {'fields': ('extra_fields',)}),
    )

This should give you what you asked for. My theory is that due to the fact that the change form already uses '__all__' fields we don't need to alter it, only add fields to the fieldsets.