无法在Django 1.5上实例化ModelForm

时间:2013-11-02 11:40:23

标签: python django django-forms

我有以下模型,包含在各自的模型中(我遵循https://docs.djangoproject.com/en/1.5/topics/forms/modelforms/上的ModelForm指南):

from django.db import models
from django.contrib.auth.models import User
from django.forms import ModelForm

class Person(models.Model):
    user = models.OneToOneField(User)
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    birth_date = models.DateField()
    address = models.CharField(max_length=100)
    email = models.CharField(max_length=50)

    class Meta:
        abstract = True

class Trainer(Person):
    team_name = models.CharField(max_length=50)

class Trainee(Person):
weight = models.DecimalField(max_digits=5,  decimal_places=2)
height = models.DecimalField(max_digits=3,  decimal_places=2)

class TrainerForm(ModelForm):
    class Meta:
        model = Trainer

class TraineeForm(ModelForm):
    class Meta:
        model = Trainee

现在我试图让视图上的表单起作用。我再次从https://docs.djangoproject.com/en/1.5/topics/forms/modelforms/

中取了示例
# Create your views here.
from django.http import HttpResponse
from django.forms.models import modelformset_factory

def index(request):
    return HttpResponse("Hello, world. You're at the users index.")

def trainer_signup(request):
    TrainerFormSet = modelformset_factory(Trainer)
    if request.method == 'POST':
        formset = TrainerFormSet(request.POST, request.FILES)
        if formset.is_valid():
            formset.save()
            # do something.
    else:
        formset = TrainerFormSet()
    return render_to_response("forms.html", {
        "formset": formset,
    })

我得到的错误是:

global name 'Trainer' is not defined

谢谢!

1 个答案:

答案 0 :(得分:1)

问题在于这行代码:

TrainerFormSet = modelformset_factory(Trainer)

因为他不知道Trainer是什么。您必须将模型导入视图中。将它添加到views.py文件的顶部,一切都可以工作:

from models import *