Django forms gives 'str' object has no attribute '_meta'

Issue

I am making a custom User model that looks like this

accounts/models.py

class MyUser(AbstractUser):
    role_tuple = (
        ('admin', 'admin'),
        ('user', 'user'),
        ('activist', 'activist'),
    )
    role = models.CharField(null = True, default='user', max_length = 200, choices = role_tuple)
    user_proof_image = models.ImageField(null=True, upload_to='user_proof_images')

Added it to settings.py

AUTH_USER_MODEL = 'accounts.MyUser'

I now want to create a form using the custom user model so I used

from django.contrib.auth.forms import UserCreationForm
from CPW.settings import AUTH_USER_MODEL

class CreateUserForm(UserCreationForm):
    class Meta:
        model = AUTH_USER_MODEL
        fields = ['username', 'email', 'password1', 'password2', 'role']

But it tells me

from .forms import CreateUserForm
  File "C:\Users\xyz\OneDrive\Desktop\Django\CPW\user_auth\forms.py", line 4, in <module>
    class CreateUserForm(UserCreationForm):
  File "C:\Users\xyz\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\models.py", line 258, in __new__
    apply_limit_choices_to=False,
  File "C:\Users\xyz\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\models.py", line 142, in fields_for_model
    opts = model._meta
AttributeError: 'str' object has no attribute '_meta'

I have never tried forms of custom users. Help?

Solution

AUTH_USER_MODEL is a string that contains the app_name.ModelName of the user model. You can use this in relations like a ForeignKey, but not in a ModelForm. You can make use of the get_user_model() function [Django-doc]:

from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm

class CreateUserForm(UserCreationForm):
    class Meta:
        model = get_user_model()
        fields = ['username', 'email', 'password1', 'password2', 'role']

Answered By – Willem Van Onsem

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published