2013-08-01 43 views
0

我創建一個表單指定,裏面forms.py我:Django的 - forms-場錯誤 - 未知領域(S)(A,L,_)爲<tablename>

from django.forms import ModelForm 
from ver11.models import studentdetails 
class studentform(ModelForm): 
    class Meta: 
      model=studentdetails 
      fields='__all__' 

但我得到以下錯誤:

Unknown field(s) (a, l, _) specified for studentdetails

請指導我通過這個

+0

顯然我已經經歷過,這就是爲什麼我在這裏問。這可能是一個愚蠢的錯誤,但它爲我創造了難度 – nerdiplayboy

+0

當我用包含studentdetails表的所有字段的列表替換__all__時,它工作正常。但是,使用'__all__'的問題是什麼 – nerdiplayboy

回答

2

我猜你是使用Django 1.5或以前的版本。 __all__只存在於Django的1.6+:

Before version 1.6, the 'all' shortcut did not exist, but omitting the fields attribute had the same effect. Omitting both fields and exclude is now deprecated, but will continue to work as before until version 1.8

因此改變你的代碼:

from django.forms import ModelForm 
from ver11.models import studentdetails 

class studentform(ModelForm): 
    class Meta: 
      model = studentdetails 
      # omit the fields totally 

也請閱讀PEP8的命名規則和風格。

+0

Thanx男:-)現在工作正常 – nerdiplayboy

+0

不客氣。如果有幫助,請接受我的回答;)。並且記得閱讀PEP8,你的代碼中的名字約定很不誠實。 –

+0

肯定的人!將盡快閱讀 – nerdiplayboy

1

在Django的1.5或之前,場應該是一個itterable,像列表或元組,你給它一個字符串,這也是一個迭代的,但它被解釋爲('a', 'l', '_')

嘗試

fields = ['__all__'] 

但是,您可以將其忽略,全部爲默認值。

另外請注意,fields = ('__all__')仍然會給你這個錯誤,因爲這不是一個真正的元組,你需要fields = ('__all__',)來說服python你的意思是一個元組。

+0

這是不正確的。雖然''fields''必須是一個可迭代的,你也可以指定'__all __'作爲它的值,並且它將包含所有'Model'的字段。檢查[文檔](https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/#selecting-the-fields-to-use)。 – alxs

+0

我相信自從django 1.7(可能是1.6/1.5?)以來這已經發生了變化,可能是因爲很多人犯了這個錯誤。但是在django 1.4中肯定不是這樣的情況https://django.readthedocs.io/en/1.4.X/topics/forms/modelforms.html我清楚地記得自己也遇到了這個問題。因爲它是默認的,所以將它保留下來的建議在我使用的所有django版本中都是有效的。 –

+0

好的,我忘記提及這是*目前*的情況。我不記得了,但我認爲它在當時有不同的表現,這就是爲什麼我沒有倒下的原因。這篇評論只是爲了讓讀者瞭解這個細節。 – alxs