Skip to content
Advertisement

Django ModelForm has no model class specified, Although model in Meta class is set to a model

Error is “ModelForm has no model class specified.”

forms.py code

from django.contrib.auth.models import User
from basic_app.models import UserProfileInfo

class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput())

    class Meta():
        models = User
        fields = ('username', 'email', 'password')

class UserProfileInfoForm(forms.ModelForm):
    class Meta():
        model = UserProfileInfo
        fields = ('portfolio_site', 'profile_pic')

models.py code

from django.db import models
from django.contrib.auth.models import User
# Create your models here.

class UserProfileInfo(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    #additional
    portfolio_site = models.URLField(blank=True)

    profile_pic = models.ImageField(upload_to='profile_pics', blank=True)

    def __str__(self):
        return self.user.username

views.py code

from django.shortcuts import render
from basic_app.forms import UserProfileInfoForm, UserForm
# Create your views here.
def index(request):
    return render(request, 'basic_app/index.html')

def register(request):

    registered = False

    if request.method == 'POST':

        user_form = UserForm(data=request.POST)
        profile_form = UserProfileInfoForm(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()

            profile = profile_form.save(commit=False)
            profile.user = user

            if 'profile_pic' in request.FILES:
                profile.profile_pic = request.FILES['profile_pic']

            profile.save()

            registered = True
        else:
            print(user_form.errors, profile_form.errors)
    else:
        user_form = UserForm()
        profile_form = UserProfileInfoForm()

    return render(request, 'basic_app/registration.html',
    {'user_form' : user_form, 'profile_form' : profile_form, 'registered' : registered})

The error is occurs when I’m trying to create a new user form (user_form = UserForm()). Although in my meta class I set models to the User model imported from django.contrib.auth.models.

Error Info Picture

Advertisement

Answer

I think your spellings in your forms are wrong could you try to correct :Changes Meta() to Meta: then models to model

class UserForm(forms.ModelForm):
   password = forms.CharField(widget=forms.PasswordInput())

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

class UserProfileInfoForm(forms.ModelForm):
   class Meta:
      model = UserProfileInfo
      fields = ('portfolio_site', 'profile_pic')
Advertisement