如何在Django中声明一个表单域,如果它与Python关键字具有相同的名称? [英] How to declare a form field in Django, if it has the same name as a Python keyword?

查看:85
本文介绍了如何在Django中声明一个表单域,如果它与Python关键字具有相同的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django中有一个简单的表单,看起来像这样:

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

由于中的是一个Python关键字,因此语法错误失败。


$ b $我不是改变字段的名字;它比任何替代品更好,我对最终用户如何看起来很诡异。 (表单正在使用GET,因此字段名称可以在URL中显示。)



我意识到我可以使用某些东西,如从_ 而是,但是我最初认为可能有一些方法来显式提供字段名称,对于这样的情况。 (例如,通过在Field构造函数中提供 name ='whatever'参数。)它转出来没有



使用动态表单生成来解决问题,这不是太糟糕,但它仍然是一个黑客...

  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_' ]

是否有更优雅的方式是将一个名为的表单字段从或任何其他Python关键字?

解决方案

不要在关键字之后命名事情,即使你找到一个工作,也可能会以后再咬你。



使用同义词或添加前缀/后缀。



例如
开始 - > 完成

开始 - > 结束

date_from - > date_to


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?

解决方案

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

这篇关于如何在Django中声明一个表单域,如果它与Python关键字具有相同的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆