Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a form field in Django, if it has the same name as a Python keyword?

Tags:

python

django

I've got a simple form in Django, that looks something like this:

class SearchForm(forms.Form):
    text = forms.CharField()
    from = forms.DateField()
    until = forms.DateField()

Which fails with a SyntaxError, because from is a Python keyword.

I rather not change the name of the field; It fits better than any of the alternatives, and I'm fussy about how it appears to the end user. (The form is using 'GET', so the field name is visible in the URL.)

I realize I could just use something, like from_ instead, but I was initially thought there might be some way to explicitly provide the field name, for cases like this. (eg. By supplying a name='whatever' parameter in the Field constructor.) It turn's out there isn't.

At the moment I'm using dynamic form generation to get around the issue, which isn't too bad, but it's still a bit of a hack...

class SearchForm(forms.Form):
    text = forms.CharField()
    from_ = forms.DateField()
    until = forms.DateField()

    def __init__(self, *args, **kwargs):
        super(SearchForm, self).__init__(*args, **kwargs)
        self.fields['from'] = self.fields['from_']
        del self.fields['from_']

Is there any more elegant way of having a form field named from, or any other Python keyword?

like image 290
Tom Christie Avatar asked Oct 14 '11 12:10

Tom Christie


1 Answers

Don't name things after keywords, even if you find a work around, it will probably end up biting you later.

Use a synonym or add a prefix/suffix instead.

E.g.
start -> finish
begin -> end
date_from -> date_to

like image 137
MattH Avatar answered Sep 28 '22 06:09

MattH