[英]How to declare a form field in Django, if it has the same name as a Python keyword?
I've got a simple form in Django, that looks something like this: 我在Django中有一个简单的表单,看起来像这样:
class SearchForm(forms.Form):
text = forms.CharField()
from = forms.DateField()
until = forms.DateField()
Which fails with a SyntaxError, because from
is a Python keyword. 哪个因SyntaxError而失败,因为
from
是一个Python关键字。
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.)
(表单使用'GET',因此字段名称在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. 我意识到我可以使用某些东西,比如
from_
,但我最初认为可能有某种方法可以明确地提供字段名称,对于这样的情况。 (eg. By supplying a name='whatever'
parameter in the Field constructor.) It turn's out there isn't . (例如,通过在Field构造函数中提供
name='whatever'
参数。)转而没有 。
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? 有有一个名为表单域的任何更优雅的方式
from
,或任何其他Python关键词?
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. 请使用同义词或添加前缀/后缀。
Eg 例如
start
-> finish
start
- > finish
begin
-> end
begin
- > end
date_from
-> date_to
date_from
- > date_to
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.