我在 forms.py 的特定模块中导入表单字段时遇到问题我有以下代码
from django import forms
from django.forms import ModelForm
from koalified.seeker.models import *
from django.contrib.auth.models import User
class RegistrationForm(ModelForm):
username = forms.CharField(label=(u'Username'))
password = forms.CharField(label=(u'Password'), widget=forms.PasswordInput(render_value=False))
ver_password = forms.CharField(label=(u' Verify Password'), widget=forms.PasswordInput(render_value=False))
email = forms.EmailField()
class Meta:
model = Seeker
exclude = ('user','verified','premium')
def clean_username(self):
''' Checking username availability '''
username = self.cleaned_data['username']
try:
User.objects.get(username=username)
except User.DoesNotExist:
if len(username) >= 5 and len(username) < 21:
return self.cleaned_data['username']
else:
raise forms.ValidationError("Username must be between 5 and 20 characters")
raise forms.ValidationError("That username is already in use")
def clean_ver_password(self):
password = self.cleaned_data.get('password')
ver_password = self.cleaned_data.get('ver_password')
if not ver_password:
raise forms.ValidationError("You must confirm your password")
if password != ver_password:
raise forms.ValidationError("Passwords do not match")
return ver_password
我不断收到一个视图不存在错误,我已经研究过,它建议进入 shell 并尝试导入。这是导入的以下输出
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/jmcguffee1/django.koalified.com/koalified/koalified/seeker/forms.py", line 6, in <module>
class RegistrationForm(ModelForm):
File "/home/jmcguffee1/django.koalified.com/koalified/koalified/seeker/forms.py", line 7, in RegistrationForm
username = forms.CharField(label=(u'Username'))
AttributeError: 'module' object has no attribute 'CharField'
我查看了一些问题,发现人们可能有拼写问题,但我一遍又一遍地尝试这个,无法让它在我的其他模块中加载表单工作得很好,比如我的登录表单
from django.contrib.auth.models import User
from django import forms
class LoginForm(forms.Form):
username = forms.CharField(label=(u'Username'))
password = forms.CharField(label=(u'Password'), widget=forms.PasswordInput(render_value=False))
我已经尝试手动导入字段并且它有效,即
from django.forms.fields import CharField, EmailField
username = CharField()
这工作正常我已经回到我的外壳并导入 django.forms 并尝试从那里加载它
from django import forms username = forms.CharField(label=(u'Username')) 用户名
我检查了我的 models.py 和 views.py 中的循环调用,并且没有其他 django 表单的导入。似乎这个特定模块没有正确加载表单字段。如果不够清楚,可以提供更多信息。
这是答案的解决方案
>>> from django import forms
>>> print 'form is : ', forms
form is : <module 'django.forms' from '/home/jmcguffee1/django.koalified.com/kf/lib/python2.6/site-packages/Django-1.4.3-py2.6.egg/django/forms/__init__.pyc'>
>>> from koalified.seeker.models import *
>>> print 'form is : ', forms
form is : <module 'django.forms.forms' from '/home/jmcguffee1/django.koalified.com/kf/lib/python2.6/site-packages/Django-1.4.3-py2.6.egg/django/forms/forms.pyc'>
>>>