Django模型表单和visible_fields

时间:2014-12-14 04:34:16

标签: python django

我正在尝试使用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):

任何指针?

1 个答案:

答案 0 :(得分:0)

将ModelForm内部exclude的{​​{1}}属性设置为要从表单中排除的字段列表。

在你的情况下,就像这样。

Meta class

请注意,在Django 1.7+中,现在需要通过class RegisterForm(forms.ModelForm): class Meta: model=User exclude = ['created_at'] 指定要排除的字段。

相关问题