0

我有以下模型,包含在他们各自的模型表单中(我正在遵循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

谢谢!

4

1 回答 1

1

问题在于这行代码:

TrainerFormSet = modelformset_factory(Trainer)

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

from models import *
于 2013-11-02T11:48:22.747 回答