Created
May 21, 2020 09:54
-
-
Save kezabelle/fc8204b30c24561004c7d8379c80fa11 to your computer and use it in GitHub Desktop.
Capture all incoming bound data which passed validation into a new querydict, such that a form can return something which may be output as a querystring where appropriate. Obviously it's not always appropriate (eg: POST forms, forms with files etc). Also I can't entirely remember how well it works for `&multiple=of&multiple=the&multiple=samething`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class F(forms.Form): | |
def to_querydict(self): | |
if not self.is_bound or not hasattr(self, 'cleaned_data'): | |
return QueryDict('') | |
qd = QueryDict('', mutable=True) | |
get_or_default = self.data.get | |
if isinstance(self.data, QueryDict): | |
get_or_default = self.data.getlist | |
for key, value in self.cleaned_data.items(): | |
prefixed_key = self.add_prefix(key) | |
if value: | |
# Sigh. If you pass in QueryDict(query_string="") to a Form | |
# subclass, you'll actually have a data attr which is a plain | |
# dictionary, and so won't have the getlist method. | |
request_val = [x for x in get_or_default(prefixed_key, ()) if x] | |
if request_val: | |
qd.setlist(prefixed_key, request_val) | |
qd._mutable = False | |
return qd |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment