Django:异常类型:IntegrityError 唯一约束失败:auth_user.username

Posted

技术标签:

【中文标题】Django:异常类型:IntegrityError 唯一约束失败:auth_user.username【英文标题】:Django: Exception Type: IntegrityError UNIQUE constraint failed: auth_user.username 【发布时间】:2020-10-10 08:05:30 【问题描述】:

我是 Django 新手,正在尝试创建一个注册应用程序,在该应用程序中通过电子邮件验证激活帐户。 我阅读了以前的帖子,但这个错误似乎有独特的原因。在我的情况下,我无法弄清楚是什么导致了这个错误。 有人可以帮我解决这个问题,或者指出正确的方向吗?


    from django.shortcuts import render, redirect
    from django.urls import reverse_lazy
    from django.views.generic import View, UpdateView
    from .forms import SignUpForm
    from django.contrib import messages
    from django.contrib.auth import login
    from django.contrib.sites.shortcuts import get_current_site
    from django.utils.encoding import force_bytes, force_text
    from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode
    from django.template.loader import render_to_string
    from .tokens import account_activation_token
    from django.contrib.auth.models import User
    from django.core.mail import EmailMessage


    class SignUpView(View):
        form_class = SignUpForm
        template_name = 'signup.html'

        def get(self, request, *args, **kwargs):
            form = self.form_class()
            return render(request, self.template_name, 'form': form)

        def post(self, request, *args, **kwargs):
            form = self.form_class(request.POST)
            if form.is_valid():
                user = form.save(commit=False)
                user.is_active = False #Deactivate account until confirmed
                user.save()

                current_site = get_current_site(request)
                subject = 'Activate Your New Account'
                message = render_to_string('activateUserEmail.html', 'user': user, 
               'domain':current_site.domain, 
               'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':
                account_activation_token.make_token(user),
                )
               user.email_user(subject, message)
               messages.success(request, ('Please confirm your email to complete 
               registration:'))
               return redirect('login')
           return render(request, self.template_name, 'form': form)

   class ActivateAccount(View):
       def get(self, request, uidb64, token, *args, **kwargs):
           try:
               uid = force_text(urlsafe_base64_encode(uidb64))
               user = User.objects.get(pk=uid)
           except (TypeError, ValueError, OverflowError, User.DoesNotExist):
               user = None

           if user is not None and account_activation_token.check_token(user, token):
               user.is_active = True
               user.profile.email_confirmed = True
               user.save()
               login(request, user)
               messages.success(request, ('Your account has been confirmed.'))
               return redirect('home')
           else:
               messages.warning(request, ('The confirmation link was invalid, possibly 
               because it has already been used or it has expired.'))

               return redirect('home')```


**Registration.Templates.Forms.html**
   ```from django.contrib.auth.forms import UserCreationForm
   from django.contrib.auth.models import User
   from django import forms
   from .models import Registration


   class SignUpForm(UserCreationForm):
       name = forms.CharField(max_length=75, required=True, help_text='First and last name 
      are required')
       ageRange = forms.ChoiceField(choices=Registration.AGE_CHOICES, required=True, 
      help_text='Select your age range')
       stateOfResidence = forms.CharField(max_length=25, required=True, help_text='Enter 
      your primary state of residence')
       profLicense = forms.CharField(max_length=25, required=True, )
       email = forms.EmailField(max_length=150, required=True,  help_text='Enter a valid 
      email address')
       password1 = forms.CharField(max_length=100, required=True,  help_text='Enter a 
      password.')

       class Meta:
           model = User
           fields = ('name', 'ageRange', 'stateOfResidence', 'profLicense', 'email', 
         'password1','password2')```


**Traceback**

Traceback (most recent call last):
  File "/Applications/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "/Applications/anaconda3/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute
    return Database.Cursor.execute(self, query, params)

The above exception (UNIQUE constraint failed: auth_user.username) was the direct cause of the following exception:
  File "/Applications/anaconda3/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/Applications/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Applications/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Applications/anaconda3/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Applications/anaconda3/lib/python3.6/site-packages/django/views/generic/base.py", line 97, in dispatch
    return handler(request, *args, **kwargs)
  File "/Users/k/Desktop/biasBasic/src/registration/views.py", line 35, in post
    user.save()
  File "/Applications/anaconda3/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 66, in save
    super().save(*args, **kwargs)
  File "/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/base.py", line 746, in save
    force_update=force_update, update_fields=update_fields)
  File "/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/base.py", line 784, in save_base
    force_update, using, update_fields,
  File "/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/base.py", line 887, in _save_table
    results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
  File "/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/base.py", line 926, in _do_insert
    using=using, raw=raw,
  File "/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/query.py", line 1204, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1392, in execute_sql
    cursor.execute(sql, params)
  File "/Applications/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute
    return super().execute(sql, params)
  File "/Applications/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/Applications/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/Applications/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "/Applications/anaconda3/lib/python3.6/site-packages/django/db/utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/Applications/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "/Applications/anaconda3/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute
    return Database.Cursor.execute(self, query, params)

Exception Type: IntegrityError at /home/signup/
Exception Value: UNIQUE constraint failed: auth_user.username

【问题讨论】:

你能发布完整的回溯吗? 是的。我添加了回溯。感谢您的评论。 您的表单中没有包含用户名字段 谢谢...您的回答很有帮助。 【参考方案1】:

我认为您每次在模型 auth_user.username 中使用相同的用户名进行检查。由于您为该用户名字段提供了主键或 (unique = true),因此它不会接受任何重复的用户名。如果这件事解决了您的问题,请回复我。

【讨论】:

我认为这是问题的一部分。我的模型和表格之间存在冲突。我基本上重写了整个应用程序,现在它正在运行......虽然我仍然不清楚所有问题是什么。我有很多要学习的。感谢您的帮助。 乐于助人?

以上是关于Django:异常类型:IntegrityError 唯一约束失败:auth_user.username的主要内容,如果未能解决你的问题,请参考以下文章

TemplateDoesNotExist at / Home.html 异常类型:TemplateDoesNotExist

使用pycharm手动搭建python语言django开发环境 django中buffer类型与str类型的联合使用

django.db.utils.ProgrammingError:无法将类型 uuid 转换为整数

Django插入:这个错误是啥意思

Django使用js,css等静态文件的时候,出现mime类型问题

Django 数据库基本查询方法