Skip to content

Commit

Permalink
Cast data to QueryDict in LinkWidget.render
Browse files Browse the repository at this point in the history
  • Loading branch information
pajowu committed Nov 27, 2024
1 parent 3656174 commit 7cd4ce6
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 7 deletions.
12 changes: 6 additions & 6 deletions django_filters/widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
from django import forms
from django.db.models.fields import BLANK_CHOICE_DASH
from django.forms.utils import flatatt
from django.http import QueryDict
from django.utils.datastructures import MultiValueDict
from django.utils.encoding import force_str
from django.utils.http import urlencode
from django.utils.safestring import mark_safe
from django.utils.translation import gettext as _

Expand Down Expand Up @@ -56,13 +56,13 @@ def render_option(self, name, selected_choices, option_value, option_label):
option_value = force_str(option_value)
if option_label == BLANK_CHOICE_DASH[0][1]:
option_label = _("All")
data = self.data.copy()

data = QueryDict(mutable=True)
data.update(self.data)
data[name] = option_value

selected = data == self.data or option_value in selected_choices
try:
url = data.urlencode()
except AttributeError:
url = urlencode(data)
url = data.urlencode()
return self.option_string() % {
"attrs": selected and ' class="selected"' or "",
"query_string": url,
Expand Down
21 changes: 20 additions & 1 deletion tests/test_widgets.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from django.forms import NumberInput, Select, TextInput
from django.test import TestCase

from django.utils.datastructures import MultiValueDict
from django_filters.widgets import (
BaseCSVWidget,
BooleanWidget,
Expand Down Expand Up @@ -143,6 +143,25 @@ def test_widget_with_blank_choice(self):
</ul>""",
)

def test_widget_multivaluedict(self):
choices = (
("", "---------"),
("test-val1", "test-label1"),
("test-val2", "test-label2"),
)

w = LinkWidget(choices=choices)
w.value_from_datadict(MultiValueDict(), {}, "price")
self.assertHTMLEqual(
w.render("price", ""),
"""
<ul>
<li><a class="selected" href="?price=">All</a></li>
<li><a href="?price=test-val1">test-label1</a></li>
<li><a href="?price=test-val2">test-label2</a></li>
</ul>""",
)

def test_widget_value_from_datadict(self):
w = LinkWidget()
data = {"price": "test-val1"}
Expand Down

0 comments on commit 7cd4ce6

Please sign in to comment.