【问题标题】:Django model form and visible_fieldsDjango 模型表单和 visible_fields
【发布时间】:2015-02-12 12:08:51
【问题描述】:

我正在尝试使用 Django 的 ModelForm,但通过使用 fields 属性来限制我显示的字段数量。这是我的代码的相关部分。

django 和 python 版本

python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> print (django.VERSION)
(1, 7, 0, 'final', 0)
>>>

models.py:

class User(AbstractBaseUser):
    name=models.CharField(max_length=255)
    email=models.CharField(max_length=255)
    password=models.CharField(max_length=255)
    created_at=models.DateTimeField(null=True, blank=True)
....

forms.py

​​>
class RegisterForm(forms.ModelForm):

    class Meta:
        model=User
        fields = ['name', 'email', 'password']

模板

  {% for field in form.visible_fields %}
        {{ field.errors }}
        {{ field.label_tag}} {{ field}}
  {% endfor %}

我发现了几个问题。

1) 当我访问该页面时,模板也显示 created_at 字段,尽管 Meta.fields 没有该列。

2) 我第一次在 shell 中导入表单类时,我看到一个弃用警告,即使我在 Meta 类中有 fields 属性

>>> from account.forms import RegisterForm
/home/django/django_project/account/forms.py:4: RemovedInDjango18Warning: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is deprecated - form RegisterForm needs updating
  class RegisterForm(forms.ModelForm):

任何指针?

【问题讨论】:

  • 你使用的是哪个 django 版本?
  • python 2.7,Django 1.7

标签: python django


【解决方案1】:

将 ModelForm 的内部 Meta classexclude 属性设置为要从表单中排除的字段列表。

在你的情况下,应该是这样的。

class RegisterForm(forms.ModelForm):

    class Meta:
        model=User
        exclude = ['created_at']

请注意,在 Django 1.7+ 中,现在需要通过 exclude 指定要排除的字段。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-27
    • 2010-12-29
    • 2014-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多