要向InlineFormsets添加自定义字段,您需要遵循以下步骤:
models.py
文件中定义您的模型和InlineFormsets。例如:from django.db import models
from django.forms import Textarea
from django.contrib import admin
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
class BookInline(admin.TabularInline): # 或者使用 admin.StackedInline
model = Book
extra = 1
admin.py
文件中,将InlineFormsets添加到您的模型管理中:from django.contrib import admin
from .models import Author, Book
class BookInline(admin.TabularInline):
model = Book
extra = 1
class AuthorAdmin(admin.ModelAdmin):
inlines = [
BookInline,
]
admin.site.register(Author, AuthorAdmin)
admin.py
文件中重写formfield_for_dbfield
方法。例如,如果您想要将Book
模型中的title
字段的widget更改为Textarea
:from django import forms
from django.contrib import admin
from .models import Author, Book
class BookInlineForm(forms.ModelForm):
class Meta:
model = Book
fields = '__all__'
widgets = {
'title': Textarea(attrs={'rows': 2, 'cols': 40}),
}
class BookInline(admin.TabularInline):
model = Book
extra = 1
form = BookInlineForm
class AuthorAdmin(admin.ModelAdmin):
inlines = [
BookInline,
]
admin.site.register(Author, AuthorAdmin)
现在,当您在Django管理界面中添加或编辑Book
对象时,title
字段将显示为Textarea
,而不是默认的文本输入框。
这就是向InlineFormsets添加自定义字段的方法。如果您需要添加其他自定义字段,只需在widgets
字典中添加更多条目即可。
领取专属 10元无门槛券
手把手带您无忧上云