我开始尝试清理我的一些代码,并且在测试时,我一直遇到这个错误:'log_in' object has no attribute 'cleaned_data'
作为背景知识,代码检查两个表单中的哪一个被提交(log_in_is_new_form()
),然后通过一些验证,例如检查它是某个主机的电子邮件地址。它返回 html 对象,这些对象向调用页面的 javascript 指示要做什么(例如显示其他表单或显示错误)。这是一个没有 JSON 的非常简单的 ajax,因为该站点非常小且流量非常低(每天最多 100 个用户。这不太可能)
def log_in_pass_match(form):
cleaned = form.cleaned_data
if cleaned['password'] == cleaned['password2']:
return true
else:
return false
def log_in_is_bbn(form):
email_bbn = form.cleaned_data['username'].split("@")
if 'bbns.org' in email_bbn:
return True
else:
return False
def log_in_is_new_form( post):
if "TN" in post:
return True
else:
return False
def log_in_already_user(form):
form.is_valid
user_object = User.objects.filter(email = form.cleaned_data['username'])
if user_object.exists():
return True
else:
return False
def log_in_send_act(form):
cleaned = form.cleaned_data['username']
msg = "sfsd"
send_mail('Activate', msg, 'michaelrgoldfine@gmail.com', [cleaned['username']], fail_silently=False)
new_user_object = User.objects.create_user(
username=cleaned_info_new['username'],
password=cleaned_info_new['password'],
email=cleaned_info_new['username']
)
def user_log_in(request):
error = []
form = log_in(request.POST)
if not log_in_already_user(form):
form = new_user(request.POST)
if log_in_is_new_form():
form_is_valid = True
other_is_valid = True
if form.is_valid():
if log_in_is_bbn(form = form) and log_in_pass_match(form = form):
other_is_valid = True
else:
other_is_valid = False
else:
form_is_valid = False
if form_is_valid and other_is_valid:
msg = "In order to activate your account at Knights of the Round Table, please click on this link:"
try:
user_object = User.objects.create_user(
username=cleaned_info_new['username'],
password=cleaned_info_new['password'],
email=cleaned_info_new['username']
)
log_in_send_act(form = form)
new_user_profile = user_object.get_profile()
new_user_profile.pen_name = form.cleaned_data['pen_name']
new_user_profile.activated = False;
new_user_profile.save()
return HttpResponse("not_act")
except:
error.append("Error Sending Email")
else:
if not other_is_valid and log_in_is_new_form(request.POST):
if log_in_is_bbn(form = form):
error.append('BBN email addresses only: [first initial][last name]@bbns.org.')
if log_in_pass_match(form = form):
error.append('Passwords do not match')
for n in form._errors:
for e in form._errors[n]:
error.append(e)
else:
return HttpResponse("n_usr")
else:
if form.is_valid():
if log_in_already_user():
logged_in_user = auth.authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password'])
if loged_in_user is not None:
if user_object[0].get_profile().activated:
auth.login(request, logged_in_user)
return HttpResponseRedirect("")
else:
return HttpResponse("not_act")
else:
error.append('Password Incorrect')
errors_template = Template("{% for e in errors %}<li>{{ e }}</li> {% endfor %}")
errors_html = errors_template.render(Context({'errors':error}))
return HttpResponse(errors_html)
完整错误:
AttributeError at /ajax/login
'log_in' object has no attribute 'cleaned_data'
Request Method: POST
Request URL: http://127.0.0.1:8000/ajax/login
Django Version: 1.4
Python Executable: /Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python
Python Version: 2.7.3
Python Path: ['/Users/Mike/Desktop/Main/Django-Development/BBN', '/Library/Python/2.7/site-packages/Django-1.4-py2.7.egg', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages', '/Library/Python/2.7/site-packages']
Server time: Tue, 7 Aug 2012 19:11:39 -0400
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'Knights',
'django.contrib.admin')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/Library/Python/2.7/site-packages/Django-1.4-py2.7.egg/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/Mike/Desktop/Main/Django-Development/BBN/Knights/views.py" in user_log_in
68. if not log_in_already_user(form):
File "/Users/Mike/Desktop/Main/Django-Development/BBN/Knights/views.py" in log_in_already_user
48. user_object = User.objects.filter(email = form.cleaned_data['username'])
Exception Type: AttributeError at /ajax/login
Exception Value: 'log_in' object has no attribute 'cleaned_data'
Request information:
GET: No GET data
POST:
username = u''
password = u'Password'
FILES: No FILES data
COOKIES:
csrftoken = 'Df1jB3708JUgretV8PSmRQ6NFQGI3wzL'
sessionid = 'c5eab78e2c73ff493056044d4e4362ba'
META:
RUN_MAIN = 'true'
HTTP_REFERER = 'http://127.0.0.1:8000/login/'
SERVER_PROTOCOL = 'HTTP/1.1'
SERVER_SOFTWARE = 'WSGIServer/0.1 Python/2.7.3'
TERM_PROGRAM_VERSION = '309'
REQUEST_METHOD = 'POST'
LOGNAME = 'Mike'
USER = 'Mike'
HTTP_ORIGIN = 'http://127.0.0.1:8000'
PATH = '/Library/Frameworks/Python.framework/Versions/3.2/bin:/Library/Frameworks/Python.framework/Versions/2.7/bin:/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'
QUERY_STRING = ''
HOME = '/Users/Mike'
wsgi.errors = <open file '<stderr>', mode 'w' at 0x100284270>
TERM_PROGRAM = 'Apple_Terminal'
LANG = 'en_US.UTF-8'
HTTP_ACCEPT_CHARSET = 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'
TERM = 'xterm-256color'
SHELL = '/bin/bash'
TZ = 'America/New_York'
HTTP_COOKIE = 'csrftoken=Df1jB3708JUgretV8PSmRQ6NFQGI3wzL; sessionid=c5eab78e2c73ff493056044d4e4362ba'
SERVER_NAME = '1.0.0.127.in-addr.arpa'
REMOTE_ADDR = '127.0.0.1'
SHLVL = '1'
wsgi.url_scheme = 'http'
_ = '/Library/Frameworks/Python.framework/Versions/2.7/bin/python'
SERVER_PORT = '8000'
PATH_INFO = u'/ajax/login'
CONTENT_LENGTH = '27'
TERM_SESSION_ID = '37C63610-0B15-480A-A5C3-1619ECABE279'
HTTP_X_REQUESTED_WITH = 'XMLHttpRequest'
SSH_AUTH_SOCK = '/tmp/launch-elZmdg/Listeners'
wsgi.input = <socket._fileobject object at 0x101bd6550>
Apple_PubSub_Socket_Render = '/tmp/launch-nMejuv/Render'
HTTP_HOST = '127.0.0.1:8000'
SCRIPT_NAME = u''
wsgi.multithread = True
HTTP_CONNECTION = 'keep-alive'
TMPDIR = '/var/folders/98/m4rlvgtx0d19gbmh824m8jt80000gn/T/'
HTTP_ACCEPT = '*/*'
wsgi.version =
HTTP_USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.57 Safari/537.1'
GATEWAY_INTERFACE = 'CGI/1.1'
wsgi.run_once = False
OLDPWD = '/Users/Mike'
wsgi.multiprocess = False
HTTP_ACCEPT_LANGUAGE = 'en-US,en;q=0.8'
__CF_USER_TEXT_ENCODING = '0x1F5:0:0'
Apple_Ubiquity_Message = '/tmp/launch-8Ck6J2/Apple_Ubiquity_Message'
PWD = '/Users/Mike/Desktop/Main/Django-Development/BBN'
DJANGO_SETTINGS_MODULE = 'BBN.settings'
CONTENT_TYPE = 'application/x-www-form-urlencoded; charset=UTF-8'
wsgi.file_wrapper = ''
REMOTE_HOST = ''
HTTP_ACCEPT_ENCODING = 'gzip,deflate,sdch'
COMMAND_MODE = 'unix2003'
Settings:
Using settings module BBN.settings
USE_L10N = True
USE_THOUSAND_SEPARATOR = False
CSRF_COOKIE_SECURE = False
LANGUAGE_CODE = 'en-us'
ROOT_URLCONF = 'BBN.urls'
MANAGERS =
DEFAULT_CHARSET = 'utf-8'
STATIC_ROOT = ''
MESSAGE_STORAGE = 'django.contrib.messages.storage.fallback.FallbackStorage'
EMAIL_SUBJECT_PREFIX = '[Django] '
FILE_UPLOAD_PERMISSIONS = None
URL_VALIDATOR_USER_AGENT = 'Django/1.4 (https://www.djangoproject.com)'
STATICFILES_FINDERS =
SESSION_COOKIE_DOMAIN = None
SESSION_COOKIE_NAME = 'sessionid'
ADMIN_FOR =
TIME_INPUT_FORMATS =
DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'TEST_MIRROR': None, 'NAME': 'database', 'TEST_CHARSET': None, 'TIME_ZONE': 'UTC', 'TEST_COLLATION': None, 'PORT': '', 'HOST': '', 'USER': '', 'TEST_NAME': None, 'PASSWORD': u'********************', 'OPTIONS': {}}}
SERVER_EMAIL = 'root@localhost'
FILE_UPLOAD_HANDLERS =
DEFAULT_CONTENT_TYPE = 'text/html'
APPEND_SLASH = True
FIRST_DAY_OF_WEEK = 0
DATABASE_ROUTERS = []
YEAR_MONTH_FORMAT = 'F Y'
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
CACHES = {'default': {'LOCATION': '', 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}
SESSION_COOKIE_PATH = '/'
USE_X_FORWARDED_HOST = False
MIDDLEWARE_CLASSES =
USE_I18N = True
THOUSAND_SEPARATOR = ','
SECRET_KEY = u'********************'
LANGUAGE_COOKIE_NAME = 'django_language'
DEFAULT_INDEX_TABLESPACE = ''
TRANSACTIONS_MANAGED = False
LOGGING_CONFIG = 'django.utils.log.dictConfig'
SEND_BROKEN_LINK_EMAILS = False
TEMPLATE_LOADERS =
WSGI_APPLICATION = 'BBN.wsgi.application'
TEMPLATE_DEBUG = True
X_FRAME_OPTIONS = 'SAMEORIGIN'
AUTHENTICATION_BACKENDS = 'django.contrib.auth.backends.ModelBackend'
FORCE_SCRIPT_NAME = None
CACHE_BACKEND = 'locmem://'
SIGNING_BACKEND = 'django.core.signing.TimestampSigner'
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_DOMAIN = None
FILE_CHARSET = 'utf-8'
DEBUG = True
SESSION_FILE_PATH = None
DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage'
INSTALLED_APPS =
LANGUAGES =
COMMENTS_ALLOW_PROFANITIES = False
STATICFILES_DIRS =
PREPEND_WWW = False
SECURE_PROXY_SSL_HEADER = None
AUTH_PROFILE_MODULE = 'Knights.UserInfo'
SESSION_COOKIE_HTTPONLY = True
DEBUG_PROPAGATE_EXCEPTIONS = False
MONTH_DAY_FORMAT = 'F j'
LOGIN_URL = '/accounts/login/'
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
TIME_FORMAT = 'P'
DATE_INPUT_FORMATS =
CSRF_COOKIE_NAME = 'csrftoken'
EMAIL_HOST_PASSWORD = u'********************'
PASSWORD_RESET_TIMEOUT_DAYS = u'********************'
CACHE_MIDDLEWARE_ALIAS = 'default'
SESSION_SAVE_EVERY_REQUEST = False
NUMBER_GROUPING = 0
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
CSRF_FAILURE_VIEW = 'django.views.csrf.csrf_failure'
CSRF_COOKIE_PATH = '/'
LOGIN_REDIRECT_URL = '/accounts/profile/'
LOGGING = {'loggers': {'django.request': {'handlers': ['mail_admins'], 'propagate': True, 'level': 'ERROR'}}, 'version': 1, 'disable_existing_loggers': False, 'filters': {'require_debug_false': {'()': 'django.utils.log.RequireDebugFalse'}}, 'handlers': {'mail_admins': {'class': 'django.utils.log.AdminEmailHandler', 'filters': ['require_debug_false'], 'level': 'ERROR'}}}
IGNORABLE_404_URLS =
LOCALE_PATHS =
TEMPLATE_STRING_IF_INVALID = ''
LOGOUT_URL = '/accounts/logout/'
EMAIL_USE_TLS = True
FIXTURE_DIRS =
EMAIL_HOST = 'smtp.gmail.com'
DATE_FORMAT = 'N j, Y'
MEDIA_ROOT = ''
DEFAULT_EXCEPTION_REPORTER_FILTER = 'django.views.debug.SafeExceptionReporterFilter'
ADMINS =
FORMAT_MODULE_PATH = None
DEFAULT_FROM_EMAIL = 'webmaster@localhost'
MEDIA_URL = ''
DATETIME_FORMAT = 'N j, Y, P'
TEMPLATE_DIRS = '/Users/Mike/Desktop/Main/Django-Development/BBN/Knights/templates'
SITE_ID = 1
DISALLOWED_USER_AGENTS =
ALLOWED_INCLUDE_ROOTS =
DECIMAL_SEPARATOR = '.'
SHORT_DATE_FORMAT = 'm/d/Y'
TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner'
CACHE_MIDDLEWARE_KEY_PREFIX = u'********************'
TIME_ZONE = 'America/New_York'
FILE_UPLOAD_MAX_MEMORY_SIZE = 2621440
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
DEFAULT_TABLESPACE = ''
TEMPLATE_CONTEXT_PROCESSORS =
SESSION_COOKIE_AGE = 1209600
SETTINGS_MODULE = 'BBN.settings'
USE_ETAGS = False
LANGUAGES_BIDI =
FILE_UPLOAD_TEMP_DIR = None
INTERNAL_IPS =
STATIC_URL = '/static/'
EMAIL_PORT = 587
USE_TZ = True
SHORT_DATETIME_FORMAT = 'm/d/Y P'
PASSWORD_HASHERS = u'********************'
ABSOLUTE_URL_OVERRIDES = {}
CACHE_MIDDLEWARE_SECONDS = 600
DATETIME_INPUT_FORMATS =
EMAIL_HOST_USER = '*****@gmail.com'
PROFANITIES_LIST = u'********************'
You're seeing this error because you have DEBUG = True in your
Django settings file. Change that to False, and Django will
display a standard 500 page.