Opened 9 years ago
Closed 9 years ago
#24788 closed New feature (fixed)
Allow Forms to set a default prefix attribute
Reported by: | Keryn Knight | Owned by: | Paweł Marczewski |
---|---|---|---|
Component: | Forms | Version: | dev |
Severity: | Normal | Keywords: | |
Cc: | django@… | Triage Stage: | Accepted |
Has patch: | yes | Needs documentation: | yes |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
Example of what I'd like to be able to do:
from django import forms class MyForm(forms.Form): field = ChoiceField(...) prefix = 'myform-is-awesome' >>> form_itself = MyForm(data=request.GET, files=None) >>> form_itself.prefix 'myform-is-awesome'
However this isn't currently workable, because self.prefix is always bound based on the argument given in the arguments, the default of which is None
By hoisting the prefix to be a class attribute, and then doing
if prefix is not None: self.prefix = prefix
it seems like forms which ship with apps could effectively namespace themselves such that N overlapping form fields could be POSTed at once and resolved to the correct form.
However, that's only a suggested use-case that hints at why it might be useful to have; the reason I specifically needed this was for validating whether a GET request was likely my filtering form, before instantiating and validating the data:
filtered_form = any(x.startswith(MyForm.prefix) for x in request.GET.keys())
so that I can selectively reset session-saved filters only when a new filterset is done (before then saving validated submitted data back into the session).
My workaround ended up looking like:
class MyForm(forms.Form): prefix = 'woo' def __init__(self, *a, *kw): super(MyForm, self).__init__(*a, **kw) self.prefix = self.__class__.prefix
which seems a bit ... rubbish.
Change History (5)
comment:1 by , 9 years ago
Triage Stage: | Unreviewed → Accepted |
---|
comment:2 by , 9 years ago
Owner: | changed from | to
---|---|
Status: | new → assigned |
comment:3 by , 9 years ago
Has patch: | set |
---|
comment:4 by , 9 years ago
Needs documentation: | set |
---|
https://github.com/django/django/pull/4707