意外的ModelForm没有指定类的错误

时间:2019-01-19 22:53:19

标签: django django-forms

所以我试图为模型创建一个表单,该表单指定我添加到User的额外字段。

forms.py

from django import forms
from .models import Profile


class ProfileForm(forms.ModelForm):
    class meta:
        model = Profile
        fields = [
            'company',
            'birth_date',
        ]

Models.py

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

class Profile(models.Model):
    user        = models.OneToOneField(User, on_delete=models.CASCADE)
    company     = models.CharField(max_length=500, blank=True)
    address     = models.CharField(max_length=30, blank=True)
    birth_date  = models.DateField(null=True, blank=True)

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

views.py

from django.shortcuts import render


from .forms import ProfileForm
from .models import Profile


def profile_settings_view(request):
    form = ProfileForm(request.POST or None)
    if form.is_valid():
        form.save()

    context = {
        'form' : form
    }
    return render(request, 'userinfo/settings.html', context)

所以我的错误输出是:

ValueError位于/ settings / 未指定ModelForm模型类。

那怎么可能,我使用了model = Profile,为什么会出现这个错误?

1 个答案:

答案 0 :(得分:0)

meta中的Meta更改为ProfileForm

元类:只是一个类容器,它定义了一些附加到模型的元数据。它定义了各种选项,例如排序,数据库表名称等。在类中包括Meta类是可选的。有关更多信息,请阅读doc