Django: Тип исключения: IntegrityError Ошибка ограничения UNIQUE: auth_user.username - PullRequest
0 голосов
/ 20 июня 2020

Я новичок в 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 Ответ

1 голос
/ 20 июня 2020

Я думаю, что вы каждый раз используете одно и то же имя пользователя в модели auth_user.username для проверки. Поскольку вы указали первичный ключ или (unique = true) для этого поля имени пользователя, оно не будет принимать повторяющиеся имена пользователей. Если эта штука решила вашу проблему, напишите мне.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...