Django 完整性错误 - 唯一约束失败

约翰·罗杰森

尝试为我的网站创建一个简单的启动页面来收集电子邮件地址。当用户提交时,它提供以下错误(以下回溯)--Unique Constraint Failed ---accounts.user.username。我想这可能与输入的电子邮件地址与用户名重叠有关,但正如您在我的帐户模型中看到的那样——用户名是从电子邮件中创建的。(注意整个用户和用户配置文件模型还没有在我的网站上使用,只是为将来的使用做准备)。任何帮助表示赞赏。谢谢

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>
阿尔皮特·索兰基

您的User模型有一个用户名字段,需要unique=True这是导致问题的原因。现在你可能有一个用户有一个用户名字段,''这是默认的。由于您已经有一个使用此用户名的用户,因此您不能再有其他用户使用此字段。您应该检查用户是否已经存在于数据库中,您还必须输入一些用户名,用户不要使用 unique=True 的默认值,这是一个非常糟糕的设计并且总是失败。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Django:完整性错误唯一约束失败:user_profile.user_id

Django多对一完整性错误

“ django.db.utils.IntegrityError:唯一约束失败:”在删除属性后仍显示错误

唯一约束失败:Django 中的 Users.username 错误

唯一约束失败 - Django

Django抛出错误django.db.utils.IntegrityError:唯一约束失败:mediaSort_userdata.user_id

Django文件上传:完整性错误

Django Postgres完整性错误

Django 1.7中的完整性错误

完整性约束冲突:外键HSQL上的唯一约束或索引冲突

Hibernate-如何捕获“完整性约束违规:唯一约束或索引违规”

迁移时出现django错误:“没有与引用表的给定键匹配的唯一约束

Django重复键值违反唯一约束错误模型形式

Django - 处理完整性错误并显示错误弹出

Django get_or_create引发完整性错误

Django 2.1发生完整性错误

django - 删除用户会引发完整性错误

django get_or_create 抛出完整性错误

SQLAlchemy:UNIQUE约束失败错误,但未设置唯一约束

具有用户唯一约束失败的Django多对一

唯一约束失败在Django中保存新obj时出错

django.db.utils.IntegrityError:唯一约束失败:mode_setting.user_id

如何在Django中捕获“唯一约束失败” 404

django.db.utils.IntegrityError:唯一约束失败:Auctions_bids.item_id

django.db.utils.IntegrityError:唯一约束失败:rango_category__new.slug

Django - 用户配置文件:唯一约束失败:main_userprofile.user_id

唯一约束失败:使用Django Framework执行登录时,authtoken_token.user_id

唯一约束失败:auth_profile.user_id Django Allauth

唯一约束的可用性