/ ModelForm的ValueError没有指定模型类

时间:2018-11-26 13:42:23

标签: python django

我创建了一个待办事项列表应用程序。当我尝试向列表中添加项目时,出现了这样的错误; 未指定ModelForm模型类。我该如何解决?

models.py

from django.db import models

class List(models.Model):
    item = models.CharField(max_length = 200)
    completed = models.BooleanField(default = False)

    def __str__(self):
        return self.item + ' | ' +  str(self.completed)

forms.py

from django import forms
from .models import List

class ListForm(forms.ModelForm):
    class Meta:
        model:List
        fields: ["item", "completed"]

views.py

from django.shortcuts import render,redirect
from .models import List
from .forms import ListForm
from django.contrib import messages

def home(request):
    if request.method == 'POST':
        form = ListForm(request.POST or None)

        if form.is_valid():
            form.save()
            all_items = List.objects.all
            messages.success(request, ('Item has been added to list'))
            return render(request, 'home.html', { 'all_items': all_items})

    else:
        all_items = List.objects.all
        return render(request,'home.html',{'all_items': all_items} )

1 个答案:

答案 0 :(得分:1)

您在问题中粘贴的这段代码是错误的:

class ListForm(forms.ModelForm):
class Meta:
    model:List
    fields: ["item", "completed"]

应更改为:

class ListForm(forms.ModelForm):
    class Meta:
        model = List  # make sure to use = and not colon ":"
        fields = ["item", "completed"]  # make sure to use = and not colon ":"

顺便说一句:List可能不是最好的类名,因为还有内置的python list