'error : can only concatenate str/tuple(not "tuple/str) to str/tuple' error in adding fields to UserCreationForm

Question:

i tried to add new fields to UserCreationForm with using CustomUserCreationForm but i get this error

TypeError:can only concatenate str(not"tuple") to str

and when i change the field to str i got the other one,

here is my code:

forms.py:

    from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm

from .models import CustomUser

class CustomUserCreationform(UserCreationForm):
    #new UsercreationForm
    class Meta(UserCreationForm):
        #new meta for UserCreationForm
        model = CustomUser 
        fields = UserCreationForm.Meta.fields + ('age',)

class CustomUserChangeForm(UserChangeForm):
    #new UserChangeForm
    model = CustomUser
    fields = UserChangeForm.Meta.fields +('age',)

admin.py:

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin

from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import CustomUser

class CustomUserAdmin(UserAdmin):
    #new UserAdmin to change defualt model
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = CustomUser
    list_display = ['email','username','age','is_staff',]

admin.site.register(CustomUser,CustomUserAdmin)

models.py:

from django.db import models
from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):
    age = models.PositiveIntegerField(null=True,blank=True)

idk whats wrong with code can u help pls?

Asked By: Nicolas_Darksoul

||

Answers:

The UserChangeForm defaults to including all fields, which uses the shortcut fields = '__all__'

When you try to do UserChangeForm.Meta.fields +('age',) you are doing '__all__' + ('age',) which is what the error you’re getting says.
Usually an error as such in Python will include a stack trace that also include the line that has the error which can help you debug such issues in the future.

If you do want all the fields, you can do

    class CustomUserChangeForm(UserChangeForm):
        #new UserChangeForm
        model = CustomUser
        fields = '__all__'

If you want specific fields be explicit

class CustomUserChangeForm(UserChangeForm):
    #new UserChangeForm
    model = CustomUser
    fields = ('first_name', 'last_name', 'email', 'age',)
Answered By: Resley Rodrigues
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.