1

我正在尝试为我拥有的模型添加额外的输入,admin.ModelAdmin以便在另一个输入发生更改时记录一些可选文本。

我无法将自定义ModelForm识别为name 'EquipmentAdmin' is not defined. 我尝试了几种不同的导入方式,但我想我一定错过了一些明显的东西。感觉 和 之间存在循环引用EquipmentAdminEquipmentAdminForm因为它们都在代码中包含对彼此的引用。

我已经创建了我的 Django 应用程序Flightdeck,并将这些都放在同一个文件夹中;

模型.py

from django.db import models

class Location(models.Model):
    name = models.CharField(max_length=45)

class Equipment(models.Model):
    unit_id = models.CharField(max_length=45)
    located = models.ForeignKey(Location)
    located_from = models.DateField()

class EquipmentLocationHistory(models.Model):
    unit = models.ForeignKey(Equipment)
    located = models.ForeignKey(Location)
    start = models.DateField()
    end = models.DateField()
    change_reason = models.CharField(max_length=45)

管理员.py

from django.contrib import admin

from flightdeck.models import *
from flightdeck.forms import EquipmentAdminForm

class EquipmentAdmin(admin.ModelAdmin):
    form = EquipmentAdminForm

    def save_model(self, request, obj, form, change):
        if 'located' in form.changed_data:
            try:
                old = Equipment.objects.get(unit_id=obj.unit_id)
            except Equipment.DoesNotExist:
                old = None

        if old:
            if 'located' in form.changed_data:
                located_history = EquipmentLocationHistory(unit=obj, located=old.located, start=old.located_from, end=obj.located_from)
                located_history.save()

        obj.save()

表格.py

from django import forms
from django.contrib import admin

class EquipmentAdminForm(forms.ModelForm):
    reason = forms.CharField()

    class Meta:
        model = EquipmentAdmin

我想reason在添加时包含该值,但由于未加载EquipmentLocationHistory而无法测试我拥有的EquipmentAdminForm内容。

4

1 回答 1

3

EquipmentAdmin不是模型。您的 ModelForm 需要参考Equipment

from django import forms
from django.contrib import admin
from flightdeck.models import Equipment

class EquipmentAdminForm(forms.ModelForm):
    reason = forms.CharField()

    class Meta:
        model = Equipment

PS:当你有循环引用时,有很多方法可以解决这个问题。模型导入和 django 的最佳方法是使用django.db.models.get_model('app', 'model')

于 2013-07-26T07:58:05.680 回答