我正在尝试为我拥有的模型添加额外的输入,admin.ModelAdmin
以便在另一个输入发生更改时记录一些可选文本。
我无法将自定义ModelForm
识别为name 'EquipmentAdmin' is not defined
. 我尝试了几种不同的导入方式,但我想我一定错过了一些明显的东西。感觉 和 之间存在循环引用EquipmentAdmin
,EquipmentAdminForm
因为它们都在代码中包含对彼此的引用。
我已经创建了我的 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
内容。