自引用表单的Django“ NameError:名称'CarImageForm'未定义”

时间:2019-10-15 21:30:00

标签: django python-3.x forms model inline-formset

我正在按照this tutorial创建对象创建表单集。目的是允许通过“异物”连接到汽车物体的多个图像以单一形式上传。

图像使用一个表单集,每个字段有一个图像,并且动态创建了许多“添加其他图像”字段。

运行服务器会引发以下错误:"NameError: name 'CarImageForm' is not defined"自引用包含定义的类时。

我仔细阅读了代码,发现了一些小的更正,但是似乎没有一个解决方案。

forms.py

from django.forms import ModelForm, ImageField, CharField, TextInput

from .models import Car, Image, CustomUser

from django.contrib.auth.forms import AuthenticationForm, UserCreationForm, UserChangeForm
from django.forms.models import inlineformset_factory

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Field, Fieldset, Div, HTML, ButtonHolder, Submit
from .custom_layout_object import Formset

class CarImageForm(ModelForm):

    class Meta:
        model = Image
        exclude = ()

    CarImageFormSet = inlineformset_factory(
        Car, Image, form=CarImageForm, fields=['car', 'image'], extra=1, can_delete=True
    )

class CreateCarForm(ModelForm):

    class Meta:
        model = Car
        exclude = ['seller']

    def __init__(self, *args, **kwargs):
        super(CarCreateForm, self).__init__(*args, **kwargs)
...  
            )
        )

Models.py(忽略不相关的部分)

class Car(models.Model):
    manufacturer = models.ForeignKey('Manufacturer', on_delete=models.SET_NULL, null=True)
    car_model = models.CharField('Model', max_length=50, null=True)
    description = models.TextField(max_length=4000)
    vin = models.CharField('VIN', max_length=17, help_text='Enter the 17 character VIN number.', blank=True, null=True)
    mileage = models.IntegerField(verbose_name='Mileage')
    date_added = models.DateTimeField(auto_now_add=True)
    engine_displacement = models.CharField(default=2.0, max_length=3, help_text="Engine displacement in Liters (E.g. 2.0, 4.2, 6.3)")
    price = models.IntegerField(default=0)

    seller = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)

    id = models.UUIDField(primary_key=True, default=uuid.uuid4,
    help_text="Unique ID for this car")
...
    drivetrain = models.CharField(
        max_length=4,
        choices = DRIVETRAIN_OPTIONS,
        blank=True,
        default='4WD',
    )

...
    transmission = models.CharField(
        max_length=4,
        choices=TRANSMISSION_OPTIONS,
        blank=True,
        default='5MT')
...
    forced_induction = models.CharField(
        max_length=4,
        choices=FORCED_INDUCTION_OPTIONS,
        default='n',
        )

    # ensures that no model year  can be set in the future. 
    model_year = models.IntegerField(validators=[MaxValueValidator(int(datetime.date.today().year) + 1)], null=True)
...

    status = models.CharField(
        max_length=1,
        choices=AVAILABILITY_STATUS,
        blank=True,
        default='a',
        help_text="Car availability",
    )

    class Meta:
        ordering = ['-date_added']
        permissions = (("can_change_availability", "Mark car as sold"),)  
...

class Manufacturer(models.Model):
    manufacturer_name = models.CharField(max_length=20)
    country_of_origin = models.CharField(max_length = 20)

    def __str__(self):
        return f'{self.manufacturer_name}'

class Image(models.Model):
    car = models.ForeignKey(Car, on_delete=models.SET_NULL, null=True)
    image = models.ImageField(upload_to=image_directory_path)


    def __str__(self):
        return str(self.car.manufacturer) + ' ' + str(self.car.car_model) + ' image'

在引发错误之前未达到视图,如果您需要查看文件,请告诉我。

1 个答案:

答案 0 :(得分:1)

删除这些行中的缩进(一个标签):

    CarImageFormSet = inlineformset_factory(
        Car, Image, form=CarImageForm, fields=['car', 'image'], extra=1, can_delete=True
    )