Django forms.py 中的正确语法?

Correct syntax in django's forms.py?

我目前正在使用 django 处理表单,并希望将另一个字段添加到表单中已有的字段中。原文为:

class NewMessageForm(forms.ModelForm):
    class Meta:
        model = Message
        fields = ['content']

我想添加另一个字段,称为 'reciever'。我在想也许我会像这样添加它:

fields = ['content'], ['reciever']

但它给了我一个错误:

File "C:\Users\Rebecca.Bi\OneDrive - St. Agnes Academy\Desktop\temp newsment\newsment-copy\env\lib\site-packages\django\forms\models.py", line 190, in if (not exclude or f not in exclude) and f not in ignored TypeError: unhashable type: 'list'

在 forms.py 中添加这个新字段的正确语法是什么?我正在使用 python 3.7

感谢您的帮助 - 任何一个都很重要!!

fields = ['content'], ['reciever'] 创建一个包含 2 个列表的元组,这在这种情况下没有意义。

错误 TypeError: unhashable type: 'list' 是由于 django 试图对 fields 中的每个元素进行哈希处理而无法对列表进行哈希处理。

相反,您应该将 'reciever' 添加到列表中:

fields = ['content', 'reciever']

顺便说一句,reciever 应该拼写为 receiver

fields 是一个包含您选择的字段的列表,就这么简单:

fields = ['content', 'reciever']

您可以在这里阅读更多内容:djangoproject modelforms