Dynamically update Django form field options using Ajax to GET new queryset

后端 未结 2 745
感动是毒
感动是毒 2021-01-13 01:04

I\'m new to coding and django and I\'m struggling to find the solution to the following problem having reviewed the answers I\'ve found.

Im creating a search form wi

相关标签:
2条回答
  • 2021-01-13 01:13

    Use ajax to send the category and retrieve subcategory elements.

    For the category, send it via get request, and using the orm return the subcategories in a json format which you can show using jQuery.

    0 讨论(0)
  • 2021-01-13 01:33

    You can't do this from Django views side, ie, backend. You could try an ajax request for implementing this kind of requests, by sending a GET request to the server for populating the drop-down or whatever you are into.

    For a simple example, you could refer here

    How do I POST with jQuery/Ajax in Django?

    EDIT

    def update_subcategories(request):
        category = request.GET.get('category', None)
        sub_category = list(SubCategory.objects.filter(category__name__exact=category).values('name'))
        return JsonResponse(dict(sub_category=sub_category))
    

    Then in ajax response you could grab it like response.data.sub_category

    0 讨论(0)
提交回复
热议问题