Opened 6 years ago

Closed 6 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


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

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 Changed 6 years ago by Tim Graham

Triage Stage: UnreviewedAccepted

comment:2 Changed 6 years ago by Paweł Marczewski

Owner: changed from nobody to Paweł Marczewski
Status: newassigned

comment:3 Changed 6 years ago by Paweł Marczewski

Has patch: set

comment:4 Changed 6 years ago by Tim Graham

Needs documentation: set

comment:5 Changed 6 years ago by Tim Graham <timograham@…>

Resolution: fixed
Status: assignedclosed

In 4df7e848:

Fixed #24788 -- Allowed Forms to specify a prefix at the class level.

Note: See TracTickets for help on using tickets.
Back to Top