gpt4 book ai didi

python - Django ModelAdmin 额外输入字段不是来自模型

转载 作者:行者123 更新时间:2023-11-30 23:34:50 25 4
gpt4 key购买 nike

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

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

我已经创建了 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

我想在添加EquipmentLocationHistory时包含reason值,但无法测试我所拥有的内容,因为EquipmentAdminForm不是'已加载。

最佳答案

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')

关于python - Django ModelAdmin 额外输入字段不是来自模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17875526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com