ModelForm has no model class specified.[django]

Viewed 175

In my forms i have:

from pydoc import locate

from django import forms
from django.conf import settings

from django.contrib.auth.forms import UserCreationForm, UsernameField
from django.core.validators import EmailValidator

class SignUpForm(UserCreationForm):
    username = UsernameField(label=_("Username"), widget=forms.TextInput(), )
    email = forms.EmailField(max_length=254, label="Email", widget=forms.EmailInput(), validators=[EmailValidator])

    class Meta:
        model = locate(settings.AUTH_USER_MODEL)   <--- HERE
        fields = ("username", "email", "password1", "password2")

in user app in models:

class Profile(AbstractUser):

    def __str__(self):
        return self.username

In my project settings.py I set up

AUTH_USER_MODEL = 'user.Profile'

And it gives me

ValueError at /user/register 
ModelForm has no model class specified.

When I change class Meta in my form to:

class Meta:

        model = Profile   <--- HERE

Everything is OK. Why my model = locate(settings.AUTH_USER_MODEL) doesnt work?

1 Answers

You can make use of the get_user_model() method [Django-doc] to get a reference to the model that you specified as AUTH_USER_MODEL:

from django.contrib.auth import get_user_model

class SignUpForm(UserCreationForm):
    username = UsernameField(
        label=_('Username'),
        widget=forms.TextInput()
    )
    email = forms.EmailField(
        max_length=254,
        label='Email',
        widget=forms.EmailInput(),
        validators=[EmailValidator]
    )

    class Meta:
        model = get_user_model()
        fields = ('username', 'email')

locate will not work in this case, since it returns None in case the module is not found, it thus "fails silently". The location of the Profile class is user.models.Profile, Django only has some special syntax app_name.ModelName it uses to refer to a model.

For another model, you can make use of the apps.get_model(…) function [Django-doc]:

from django.apps import apps
from django import forms

# name of the model
model_name = 'app_name.ModelName'

class MyModelForm(forms.ModelForm):
    class Meta:
        model = apps.get_model(model_name)
        fields = '__all__'
Related