limit the choices for objects related to the chosen in the select

无人久伴 提交于 2019-12-11 07:02:28

问题


I wonder if anyone would know a way to return the categories related to the session chosen in the select options.

Example:

class Session(models.Model):
    name = models.CharField("Sessão", max_length=100)
    slug = models.SlugField("Slug", max_length=100)

class Category(models.Model):
    session = models.ForeignKey(Session, verbose_name='Sessão', on_delete=models.CASCADE, max_length=100, default=1, blank=True, null=True)
    category = models.CharField("Categoria", max_length=100)
    slug = models.SlugField("Slug", max_length=100)

class Article(models.Model):
    category = models.ForeignKey(Category, verbose_name='Categoria', on_delete=models.CASCADE, max_length=100, default=1, blank=True, null=True)
    session = models.ForeignKey(Session, verbose_name='Sessão', on_delete=models.CASCADE, max_length=100, default=1, blank=True, null=True)

When registering an Article, I would define a session for the article, and then I would like to return categories, only the categories related to that session.

Can anybody help me ? I believe this would have to be dynamically ...

Strong hug!


回答1:


1st solution:

Override the template (Django Documentation can help you with that)

Onchange of the field, you need to make an ajax call to an API which takes in session_id and returns you all the categories. Fill the returned result into categories through JS.

Also, you can give a try to django-ajax-selects

2nd solution: (without JS/AJAX)

To register an article, You can first go to session admin and then have a link there to add an article.

a. If you want to do it changeform_view then, You can use inline admin and override its form init() to prepopulate the categories.

b. If you want the link in changelist_view,

http://localhost:8000/admin/<app>/article/add/?session_id=<>

You can override the Article Admin form init() and read the session_id passed and use it accordingly.



来源:https://stackoverflow.com/questions/50799470/limit-the-choices-for-objects-related-to-the-chosen-in-the-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!