2012-08-08 101 views
0

我有一個網站運行的Ajax調用不使用JSON(因爲該網站是如此之小)。它首先檢查用戶是否通過他們的電子郵件註冊,如果沒有,他們會在登錄前被JS提示更多信息。這應該確保用戶名始終是唯一的,因爲如果不是,它會重定向你到不同的事情。不知何故,每個用戶名我輸入測試它結束了以下錯誤column username is not unique Django抱怨用戶名字段不是唯一的,當它是

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) 

models.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'[email protected]' 
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 = '[email protected]' 
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 
' 
+2

引發的異常與用戶名不是唯一的,而是關於用戶名=已清除['用戶名']的調用有關。看起來,**清理**參數不是一個字典,因爲它應該是一個字符串,因此錯誤:字符串索引必須是整數。在log_in_send_act函數中添加:print type(clean)'。如果我是對的,它應該告訴你它是一個字符串。然後打印它的值,以便我們可以有更多的細節。 – 2012-08-08 02:30:56

+0

@lcfseth呃,這很不幸。我發佈了錯誤的一組錯誤。 – 2012-08-08 02:34:11

+0

@lcfseth現在已修復。 – 2012-08-08 02:35:33

回答

3

難只看代碼就知道,但是:

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'] 
) 

如果我取代它的代碼log_in_send_act,這將成爲:以完全相同的參數User.create_user功能

cleaned = form.cleaned_data 
msg = "To activate your account, please click the following link:<a ref='"+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'] 
) 

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'] 
) 

隨着2連續調用。即使數據未提交到數據庫,如果Django執行數據庫(如內存檢查),這可能會引發錯誤。

+0

我甚至沒有注意到。謝謝 – 2012-08-08 02:52:15

+0

歡迎您:)祝您好運。 – 2012-08-08 02:54:38

相關問題