开发者

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

开发者 https://www.devze.com 2023-04-12 20:12 出处:网络
I\'ve got a simple form in Django, that looks something like this: class SearchForm(forms.Form): text = forms.CharField()

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_开发者_JAVA技巧 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?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号