我正在尝试自定义django注册表单。而我的forms.py看起来像这样:
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class MyRegistrationForm(UserCreationForm):
first_name=forms.CharField(max_length=120, required=True,label='First Name')
last_name=forms.CharField(max_length=120, required=True,label='Last Name')
email=forms.EmailField(label='Email Address')
company_or_institution=forms.CharField(max_length=120, required=True,label='Company or Institution Name')
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2')
def save(self,commit = True):
user = super(MyRegistrationForm, self).save(commit = False)
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']
user.company_or_institution = self.cleaned_data['company_or_institution']
if commit:
user.save()
return user
我的views.py是
def register_user(request):
if request.method == 'POST':
form = MyRegistrationForm(request.POST)
print form.is_valid()
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
args = {}
args.update(csrf(request))
args['form'] = MyRegistrationForm()
return render(request, 'register.html', args)
但是当我从终端(python forms.py)测试我的forms.py时,我收到以下错误:
Traceback (most recent call last):
File "forms.py", line 8, in <module>
from django.contrib.auth.models import User
File "/usr/local/lib/python2.7/dist-packages/django/contrib /auth/__init__.py", line 7, in <module>
from django.middleware.csrf import rotate_token
File "/usr/local/lib/python2.7/dist-packages/django/middleware/csrf.py", line 14, in <module>
from django.utils.cache import patch_vary_headers
File "/usr/local/lib/python2.7/dist-packages/django/utils/cache.py", line 26, in <module>
from django.core.cache import caches
File "/usr/local/lib/python2.7/dist-packages/django/core/cache/__init__.py", line 34, in <module>
if DEFAULT_CACHE_ALIAS not in settings.CACHES:
File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 48, in __getattr__
self._setup(name)
File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 42, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured:请求设置CACHES,但未配置设置。您必须先定义环境变量DJANGO_SETTINGS_MODULE或在访问设置之前调用settings.configure()。
任何人都知道如何解决这个问题? 感谢
答案 0 :(得分:0)
这与您的表单或任何代码无关。
如果您要使用Django,则应使用python manage.py shell
启动终端,以便正确设置环境。