Django:根据选择选项更改内联
类别具有“类型”(例如,三种类型的类别)。每个类别可以有任意数量的视频。并且在“1”类型的类别中发布的每个视频可以具有任意数量的图片。但对于以“2”和“3”类别类型发布的视频,没有图片。
models.py:
class Category(models.Model):
title = models.CharField()
CHOICES = (
('1','1'),
('2','2'),
('3','3'),
)
type = models.CharField(choices=CHOICES)
class Video(models.Model):
category = models.ForeignKey(Category)
class Picture(models.Model):
video = models.ForeignKey(Video)
title = models.Charfield()
admin.py:
class PictureInline(admin.TabularInline):
model = Picture
extra = 5
class VideoAdmin(admin.ModelAdmin):
inlines = [PictureInline,]
问题:
当我添加视频项目并为其选择类别时,如何动态显示基于PictureInline的我为视频选择了什么类型的类别?
如果我在选择列表中选择第一个类别,我希望能够在管理中看到 PictureInline,如果我选择其他类别,我不想看到 PictureInline。
是否可以?
PS:我发现https://github.com/digi604/django- smart-selects 但没有找到这样的内联功能
Category has "types" (for example, three types of categories). Each category may have any number of Videos. And each Video, published in Category of '1' type may have any number of Pictures. But for Video, published in '2' and '3' Category types there are no Pictures.
models.py:
class Category(models.Model):
title = models.CharField()
CHOICES = (
('1','1'),
('2','2'),
('3','3'),
)
type = models.CharField(choices=CHOICES)
class Video(models.Model):
category = models.ForeignKey(Category)
class Picture(models.Model):
video = models.ForeignKey(Video)
title = models.Charfield()
admin.py:
class PictureInline(admin.TabularInline):
model = Picture
extra = 5
class VideoAdmin(admin.ModelAdmin):
inlines = [PictureInline,]
question:
When i add Video item, and selecting Category for it, how can i dinamically show PictureInline based on what type of Category i selected for Video?
If i select first Category in select list, i want to be ablle to see PictureInline in admin, and if i select other Categories, i didn't want to see PictureInline.
Is it possible?
PS: I found https://github.com/digi604/django-smart-selects but didn't find such functionality for inlines
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需使用 JavaScript 动态隐藏/显示内联集。内联集的 id 始终为
#[lated_name]-group
。yourapp/views.py
将以下内容添加到
VideoAdmin
:或使用以下内容覆盖
templates/yourapp/video/change_form.html
:更新:
我已经更改了上面的 JavaScript 以包含 AJAX 请求。您将必须使用 AJAX,因为您必须先获取所选类别,然后才能获取其类型。我还添加了一个基本视图,您可以使用它来返回所需的数据。您只需将视图挂接到 urls.py 中,并更改 AJAX 调用中的 URL 以进行匹配。
Just use JavaScript to dynamically hide/show the inline set. The id of the inline set is always
#[related_name]-group
.yourapp/views.py
Add the following to
VideoAdmin
:Or override
templates/yourapp/video/change_form.html
with:UPDATE:
I've changed the JavaScript above to include an AJAX request. You're going to have to use AJAX because you've got to fetch the selected Category before you can get the type of it. I've also added a basic view you can use to return the data you need. You just need to hook the view up in your urls.py and change the URL in the AJAX call to match.