简体   繁体   English

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

[英]Django: Exception Type: IntegrityError UNIQUE constraint failed: auth_user.username

I am new to Django, and trying to create a registration app where account is activated upon email verification.我是 Django 的新手,并尝试创建一个注册应用程序,在 email 验证后激活帐户。 I read previous posts, but there seems to be unique reasons for this error.我阅读了以前的帖子,但这个错误似乎有独特的原因。 I cannot figure out what is causing this error in my case.在我的情况下,我无法弄清楚是什么导致了这个错误。 Can someone troubleshoot this for me, or point me in the right direction?有人可以为我解决这个问题,或者指出我正确的方向吗?


    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

I think you are using the same username every time in model auth_user.username for your checking purpose.我认为您每次在 model auth_user.username 中使用相同的用户名进行检查。 As you have given primary key or (unique = true) to that username field, it won't accept any duplicated usernames.由于您已为该用户名字段提供主键或 (unique = true),因此它不会接受任何重复的用户名。 If this thing solved your problem ping me back.如果这件事解决了您的问题,请回复我。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 /signup UNIQUE 约束的 IntegrityError 失败:auth_user.username - IntegrityError at /signup UNIQUE constraint failed: auth_user.username Django tests.py django.db.utils.IntegrityError:唯一约束失败:auth_user.username - Django tests.py django.db.utils.IntegrityError: UNIQUE constraint failed: auth_user.username django.db.utils.IntegrityError:唯一约束失败:auth_user.username - django.db.utils.IntegrityError: UNIQUE constraint failed: auth_user.username Django错误:UNIQUE约束失败:auth_user.username - Django error: UNIQUE constraint failed: auth_user.username UNIQUE约束失败:auth_user.username - UNIQUE constraint failed: auth_user.username 如何捕获UNIQUE约束失败:auth_user.username错误? - How to catch UNIQUE constraint failed: auth_user.username error? 如何修复错误 UNIQUE constraint failed: auth_user.username - how to fix error UNIQUE constraint failed: auth_user.username UNIQUE 约束失败:auth_user.username 尝试在 django 中注册用户时 - UNIQUE constraint failed: auth_user.username while trying to register the user in django 唯一约束失败:创建 django 注册表单时的 auth_user.username - UNIQUE constraint failed: auth_user.username when creatin a django sign up form 如何解决Django中的错误“ / admin / auth / user / add / UNIQUE约束失败的IntegrityError:user_details_profile.phone”? - How do I solve the error 'IntegrityError at /admin/auth/user/add/ UNIQUE constraint failed: user_details_profile.phone' in Django?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM