我有一个使用不使用 JSON 的 ajax 调用的网站(因为该网站太小了)。它首先检查用户是否通过他们的电子邮件注册,如果没有,JS 会在他们登录之前提示他们提供更多信息。这应该在某种程度上确保用户名始终是唯一的,因为如果没有,它会重定向你要另当别论。不知何故,我输入来测试它的每个用户名最终都会出现以下错误column username is not unique
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' == email_bbn[1]:
return True
else:
return False
def log_in_is_new_form(r):
if "TN" in r:
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
msg = "To activate your account, please click the following link:<a href='"+get_random_word()+"'>Click Here</a>"
send_mail('Activate', msg, '****@gmail.com', [cleaned['username']], fail_silently=False)
new_user_object = User.objects.create_user(
username=cleaned['username'],
password=cleaned['password'],
email=cleaned['username']
)
def log_in_form_check(form, error):
if form.is_valid():
return True
else:
for n in form._errors:
for e in form._errors[n]:
error.append(e)
return False
def user_log_in(request):
error = []
form = log_in(request.POST)
form_check = log_in_form_check(form, error)
if form_check:
if not log_in_already_user(form):
form = new_user(request.POST)
if log_in_is_new_form(request.POST):
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:
log_in_send_act(form = form)
print form.cleaned_data['username']
user_object = User.objects.create_user(
username=form.cleaned_data['username'],
password=form.cleaned_data['password'],
email=form.cleaned_data['username']
)
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 not log_in_is_bbn(form = form):
error.append('BBN email addresses only.')
if not 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")
elif form_check:
logged_in_user = auth.authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password'])
if logged_in_user is not None:
if logged_in_user.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)
模型.py:
def create_user_info(sender, instance, created, **kwargs):
if created:
UserInfo.objects.create(user=instance)
post_save.connect(create_user_info, sender=User)
class UserInfo(models.Model):
user = models.OneToOneField(User, related_name='info')
pen_name = models.CharField(max_length=30)
activated = models.BooleanField()
activation_key = models.CharField(max_length=40)
def __unicode__(self):
return self.email + '-' + self.pen_name
这是完整的错误:
IntegrityError at /ajax/login
column username is not unique
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 22:34:35 -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
109. email=form.cleaned_data['username']
File "/Library/Python/2.7/site-packages/Django-1.4-py2.7.egg/django/contrib/auth/models.py" in create_user
160. user.save(using=self._db)
File "/Library/Python/2.7/site-packages/Django-1.4-py2.7.egg/django/db/models/base.py" in save
463. self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/Library/Python/2.7/site-packages/Django-1.4-py2.7.egg/django/db/models/base.py" in save_base
551. result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
File "/Library/Python/2.7/site-packages/Django-1.4-py2.7.egg/django/db/models/manager.py" in _insert
203. return insert_query(self.model, objs, fields, **kwargs)
File "/Library/Python/2.7/site-packages/Django-1.4-py2.7.egg/django/db/models/query.py" in insert_query
1576. return query.get_compiler(using=using).execute_sql(return_id)
File "/Library/Python/2.7/site-packages/Django-1.4-py2.7.egg/django/db/models/sql/compiler.py" in execute_sql
910. cursor.execute(sql, params)
File "/Library/Python/2.7/site-packages/Django-1.4-py2.7.egg/django/db/backends/util.py" in execute
40. return self.cursor.execute(sql, params)
File "/Library/Python/2.7/site-packages/Django-1.4-py2.7.egg/django/db/backends/sqlite3/base.py" in execute
337. return Database.Cursor.execute(self, query, params)
Exception Type: IntegrityError at /ajax/login
Exception Value: column username is not unique
Request information:
GET: No GET data
POST:
username = u'mgodfd@bbns.org'
TN = u'TN'
password2 = u'fff'
password = u'fff'
pen_name = u'fff'
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 = '72'
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 0x101be8cd0>
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
'