我有一个文章模型,我写了一些文章。另外,在我的网站中,我有一个带有3个图像的滑块。我创建了一个模型。
class SliderImages(models.Model):
class Meta():
db_table = 'slider'
image_1 = models.ImageField()
image_2 = models.ImageField()
image_3 = models.ImageField()
如何用一些文章绑定每个图像?在django admin中,我想上传图片并将其绑定到一些文章,然后在滑块中每个图片都会有一个指向某篇文章的链接
更新帖子:
理想情况(一张图片一张)
代码: 机型:
class Slider(models.Model):
article = models.ManyToManyField(Article)
class SliderImages(models.Model):
slider = models.ForeignKey(Slider, null = True, related_name= '+')
article = models.ForeignKey(Article, null = True, related_name= '+')
image = models.ImageField()
class Meta():
db_table = 'slider'
并在admin.py中:
class SliderInline(admin.TabularInline):
model = SliderImages
max_num = 3
class SliderAdmin(admin.ModelAdmin):
inlines = [SliderInline,]
admin.site.register(Slider, SliderAdmin)
答案 0 :(得分:0)
只需添加一个ForeignKey
与您要绑定的模型对象,并将正常的Django绑定设置为该文章对象:
class SliderImages(models.Model):
class Meta():
db_table = 'slider'
article = models.ManyToManyField(Article)
image_1 = models.ImageField()
image_2 = models.ImageField()
image_3 = models.ImageField()
答案 1 :(得分:0)
只需在文章中添加三个外键:
class SliderImages(models.Model):
class Meta:
db_table = 'slider'
article = models.ManyToManyField(Article)
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
中的字段集将image_N / article_N放在一行中:
class SliderImagesAdmin(admin.ModelAdmin):
fieldsets = (
(None, {
'fields': ('article', ('image_1', 'article_1'),
('image_2', 'article_2'),
('image_3', 'article_3'),)
}),
)
admin.site.register(SliderImages, SliderImagesAdmin)
答案 2 :(得分:0)
如果您想为每篇文章分配一些图像,那么:
class SliderImages(models.Model):
article = models.ForeignKey(Article)
image = models.ImageField()
class Meta():
db_table = 'slider'
然后在管理员中,您将SliderImages设为内联文章,请参阅https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.StackedInline
class SliderInline(admin.TabularInline):
model = SliderImages
max_num = 3
class ArticleAdmin(admin.ModelAdmin):
inlines = [
SliderInline,
]