2017-07-29 39 views
0

試圖爲我的網站創建一個簡單的啓動頁面來收集電子郵件地址。當用戶提交時,它提供以下錯誤(下面的追蹤) - 唯一約束失敗--- accounts.user.username。我想這可能與輸入的電子郵件地址與用戶名重疊有關,但正如您在我的賬戶模型中所看到的 - 用戶名是通過電子郵件創建的。 (請注意,整個用戶和用戶個人資料模型尚未在我的網站中使用,但僅爲將來的使用做準備)。任何幫助表示讚賞。由於Django完整性錯誤 - 唯一約束失敗

Traceback (most recent call last): 
    File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 149, in get_response 
    response = self.process_exception_by_middleware(e, request) 
    File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 147, in get_response 
    response = wrapped_callback(request, *callback_args, **callback_kwargs) 
    File "C:\Users\crstu\PycharmProjects\dealmazing\dealmazing\views.py", line 15, in newsletter_signup 
    instance.save() 
    File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\base_user.py", line 74, in save 
    super(AbstractBaseUser, self).save(*args, **kwargs) 
    File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 708, in save 
    force_update=force_update, update_fields=update_fields) 
    File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 736, in save_base 
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) 
    File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 820, in _save_table 
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) 
    File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 859, in _do_insert 
    using=using, raw=raw) 
    File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\manager.py", line 122, in manager_method 
    return getattr(self.get_queryset(), name)(*args, **kwargs) 
    File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 1039, in _insert 
    return query.get_compiler(using=using).execute_sql(return_id) 
    File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\compiler.py", line 1060, in execute_sql 
    cursor.execute(sql, params) 
    File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 79, in execute 
    return super(CursorDebugWrapper, self).execute(sql, params) 
    File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute 
    return self.cursor.execute(sql, params) 
    File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\utils.py", line 95, in __exit__ 
    six.reraise(dj_exc_type, dj_exc_value, traceback) 
    File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\six.py", line 685, in reraise 
    raise value.with_traceback(tb) 
    File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute 
    return self.cursor.execute(sql, params) 
    File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 323, in execute 
    return Database.Cursor.execute(self, query, params) 
django.db.utils.IntegrityError: UNIQUE constraint failed: accounts_user.username 

我的帳戶的應用程序如下模式:

from django.contrib.auth.models import (
    AbstractBaseUser, 
    BaseUserManager, 
    PermissionsMixin 
) 
from django.db import models 
from django.utils import timezone 
from django.conf import settings 
from django.db.models.signals import post_save 
import os 


def avatar_upload_path(instance, filename): 
    return os.path.join('avatars', 'user_{0}', '{1}').format(
     instance.user.id, filename) 


class UserManager(BaseUserManager): 
    def create_user(self, email, username=None, password=None): 
     if not email: 
      raise ValueError("Users must have an email address") 

     if not username: 
      username = email.split('@')[0] 

     user = self.model(
      email=self.normalize_email(email), 
      username=username, 
     ) 
     user.set_password(password) 
     user.save() 
     return user 

    def create_superuser(self, email, username, password): 
     user = self.create_user(
      email, 
      username, 
      password, 
     ) 
     user.is_staff = True 
     user.is_superuser = True 
     user.save() 
     return user 


class User(AbstractBaseUser, PermissionsMixin): 
    email = models.EmailField(unique=True) 
    username = models.CharField(max_length=40, unique=True, default='') 
    date_joined = models.DateTimeField(default=timezone.now) 
    is_active = models.BooleanField(default=True) 
    is_staff = models.BooleanField(default=False) 

    objects = UserManager() 

    USERNAME_FIELD = 'email' 
    REQUIRED_FIELDS = ['username'] 

    def __str__(self): 
     return "@{}".format(self.username) 

    def get_short_name(self): 
     return self.username 

    def get_long_name(self): 
     return "@{} ({})".format(self.username, self.email) 


class UserProfile(models.Model): 
    user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True, related_name='profile') 
    first_name = models.CharField(max_length=40, default='', blank=True) 
    last_name = models.CharField(max_length=40, default='', blank=True) 
    bio = models.TextField(blank=True, default='') 
    avatar = models.ImageField('Avatar picture', 
           upload_to=avatar_upload_path, 
           null=True, 
           blank=True) 

    def __str__(self): 
     return self.user.username 

    @property 
    def get_avatar_url(self): 
     if self.avatar: 
      return '/media/{}'.format(self.avatar) 
     return 'http://www.gravatar.com/avatar/{}?s=128&d=identicon'.format(
      '94d093eda664addd6e450d7e9881bcad' 
     ) 


def create_profile(sender, **kwargs): 
    if kwargs['created']: 
     user_profile = UserProfile.objects.create(user=kwargs['instance']) 

post_save.connect(create_profile, sender=User) 

,這裏是我所收集電子郵件地址,實際通訊的看法。請注意我只是暫時重定向現在谷歌作爲一個測試:

from django.shortcuts import render, redirect 
from newsletters.forms import NewsletterUserSignUpForm 
from accounts.models import User 


def newsletter_signup(request): 
    if request.method == "POST": 
     form = NewsletterUserSignUpForm(request.POST) 

     if form.is_valid(): 
      instance = form.save(commit=False) 
      if User.objects.filter(email=instance.email).exists(): 
       print("Sorry this email already exists") 
      else: 
       instance.save() 
       return redirect("http://www.google.com") 

    else: 
     form = NewsletterUserSignUpForm() 

    template = "newsletters/sign_up.html" 
    return render(request, template, {'form': form}) 

註冊的HTML表單如下:

<div class="col-lg-6 offset-lg-3"> 
     <form method="POST"> 
     {% csrf_token %} 
     <div class="form-group"> 
      <div class="col-xs-6 col-xs-offset-3"> 
      {{ form.email}} 
     <button class="btn btn-primary" type="submit">Sign Up!</button> 
      </div> 
     </div> 
     </form> 
     </div> 
    </div> 

回答

1

User模型用戶名字段需要unique=True這是你的問題的原因。現在你可能會有一個用戶名爲''的用戶名字段,這是默認的。由於您已擁有一位擁有此用戶名的用戶,因此您無法讓其他用戶使用此字段。你應該檢查該用戶已經存在於數據庫中,或者你不得不向用戶輸入一些用戶名,不要使用default with unique = True,這是一個非常糟糕的設計,總是失敗。

+0

好的我認爲你肯定是在這條正確的道路上。數據庫中已經有兩個用戶 - 一個是超級用戶,另一個用戶名是默認的用戶名。當我用空白的用戶名輸入這個用戶的用戶名時,表單工作。所以,我刪除了默認值=''但是當我在表單中輸入一個新的用戶電子郵件時,問題不斷髮生。我是否需要將用戶名設置爲註冊表單視圖中的電子郵件地址? –

+0

您必須在表格中輸入用戶名字段,並在保存用戶存在與否之前進行檢查。如果可能會發現用戶名已經以dB爲單位存在,也不要使用戶名不在電子郵件中。從用戶名採取用戶名,並檢查它是否存在,如果它不存在然後繼續創建用戶 –

+0

我唯一的問題是,我只是試圖創建一個臨時通訊註冊表單 - 唯一的輸入會是電子郵件,所以不會從用戶那裏收集用戶名。 –

2

因爲您正在使用username = email.split('@')[0]獲取用戶的用戶名。有可能兩個不同的電子郵件會爲您提供username的相同值。例如[email protected][email protected]。你需要做的是找出一些其他的算法來設置username或者一個好主意可以是將用戶email作爲用戶名。

+0

電子郵件的好用戶名。這就是我總是做什麼.. –

+0

我不認爲這是問題 - 因爲我已經多次測試它與許多不同的電子郵件,並仍然得到同樣的錯誤的一切 –

相關問題