我有一个名为 Employee 的模型,其定义如下:
class Employee(models.Model):
created = models.DateTimeField(auto_now_add=True)
name = models.CharField("Name", max_length=255)
address = models.CharField("Address", max_length=255)
department = models.ForeignKey(Department, on_delete=models.SET_NULL)
team = models.ForeignKey(Team, on_delete=models.SET_NULL)
position = models.ForeignKey(Position, on_delete=models.SET_NULL)
有没有办法在 django-admin 表单中为同一部门、团队和职位添加多个员工姓名和地址?我想要类似表单集的东西,包括模型 Employee 的字段名称和地址,您可以在其中输入部门、团队和职位,然后像内联一样多次添加表单集。
我还没有尝试过任何东西。
您可以通过使用内联表单集在 Django 管理中执行此操作。在您的情况下,您希望在 Django 管理表单中允许同一部门、团队和职位的多个名称和地址条目。
from django import forms
from django.contrib import admin
from django.forms.models import inlineformset_factory
from .models import Employee, Department, Team, Position
class EmployeeInlineForm(forms.ModelForm):
class Meta:
model = Employee
fields = ['name', 'address']
EmployeeInlineFormSet = inlineformset_factory(
Department, # Parent model (change to Team or Position as needed)
Employee,
form=EmployeeInlineForm,
extra=1, # Number of empty forms to display
can_delete=True,
)
class EmployeeInline(admin.TabularInline): # Use 'StackedInline' for a different layout
model = Employee
formset = EmployeeInlineFormSet
extra = 1 # Number of empty forms to display
class DepartmentAdmin(admin.ModelAdmin):
inlines = [EmployeeInline]
admin.site.register(Department, DepartmentAdmin)