In a Django template, how to specify a dictionary key which is itself an attribute?

前端 未结 2 2002
感动是毒
感动是毒 2021-01-25 15:07

I\'m working on a Django project with a ListView that has both a search form, known in the view\'s context as search_form, and a filter form, fil

2条回答
  •  北恋
    北恋 (楼主)
    2021-01-25 15:48

    So it basically boils down to not submitting keys in the GET request that have an empty string value. This appears to be unsupported natively in HTML; you need some JS magic to make this happen. See this thread: How to prevent submitting the HTML form's input field value if it empty

    However, a pure Django solution would be to modify your filter dict to exclude keys that are null. I am not sure how you are filtering this in Django, but assuming you have override the get_queryset method; you can always do:

    def get_queryset(self):
        qs = super(YourView, self).get_queryset()
        filters = {k, v for k, v in request.GET.items() if v != ''}  # Be as generic/specific as needed here for exclusion
        qs = qs.filter(**filters)  # Fire your filtering logic here; this is a sample
        return qs
    

提交回复
热议问题