我有一个上传滑块图片的模型,并将这些图片与一些文章绑定。
class SliderImages(models.Model):
class Meta():
db_table = 'slider'
image_1 = models.ImageField()
image_2 = models.ImageField()
image_3 = models.ImageField()
article_1 = models.ForeignKey(Article, related_name='+')
article_2 = models.ForeignKey(Article, related_name='+')
article_3 = models.ForeignKey(Article, related_name='+')
然后在admin.py中写道:
class SliderImagesAdmin(admin.ModelAdmin):
fieldsets = (
(None, {
'fields': (('image_1', 'article_1'),
('image_2', 'article_2'),
('image_3', 'article_3'),)
}),
)
admin.site.register(SliderImages, SliderImagesAdmin)
它运作良好,没关系。但是图像文章的数量是有限的(3)。我希望管理员决定添加新文章的图片文章数量。 我认为新模型看起来应该是这样的:
class SliderImages(models.Model):
class Meta():
db_table = 'slider'
image = models.ImageField()
article = models.ForeignKey(Article, related_name='+')
我想我应该使用inlines
,但不知道如何
答案 0 :(得分:0)
<强> models.py 强>
from django.utils.translation import ugettext_lazy as _
class Slider(models.Model):
title = models.CharField(_('title'), max_length=255, null=True, blank=True)
class Meta():
db_table = 'slider'
class SliderItems(models.Model):
slider = models.ForeignKey(Slider, related_name='slider_items')
image = models.ImageField()
article = models.ForeignKey(Article, related_name='+')
<强> admin.py 强>
from django.contrib import admin
from .models import Slider, SliderItems
class SliderItemsInline(admin.TabularInline):
model = SliderItems
class SliderAdmin(admin.ModelAdmin):
inlines = [
SliderItemsInline,
]
admin.site.register(Slider, SliderAdmin)
请参阅https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.InlineModelAdmin