我正在尝试为我拥有的模型添加一个额外的输入admin.ModelAdmin
,这样我可以在另一个输入发生变化时记录一些可选文本。
我无法将自定义ModelForm
识别为name 'EquipmentAdmin' is not defined
。我尝试了几种不同的导入方式,但我想我一定错过了一些明显的东西。感觉EquipmentAdmin
和EquipmentAdminForm
之间存在循环引用,因为它们在代码中都包含对彼此的引用。
我创建了我的Django应用程序Flightdeck
并将它们全部放在同一个文件夹中;
models.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)
admin.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()
forms.py
from django import forms
from django.contrib import admin
class EquipmentAdminForm(forms.ModelForm):
reason = forms.CharField()
class Meta:
model = EquipmentAdmin
我希望在添加reason
时添加EquipmentLocationHistory
值,但无法测试我的内容,因为EquipmentAdminForm
未加载。
答案 0 :(得分: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')