IntegrityError at /signup UNIQUE constraint failed: auth_user.username
Я пытаюсь сделать систему аутентификации с помощью Django, используя только 3 поля для регистрации (имя пользователя & email & password) и 2 поля для входа в систему (имя пользователя & password). Я думаю, что ошибка, которую я получаю, связана с базой данных, которую я еще не использовал в файле моделей, я не знаю, откуда исходит проблема, из функции регистрации или из функции подписи
IntegrityError at /signup
UNIQUE constraint failed: auth_user.username
Request Method: POST
Request URL: http://127.0.0.1:8000/signup
Django Version: 3.2.6
Exception Type: IntegrityError
Exception Value:
UNIQUE constraint failed: auth_user.username
Exception Location: C:\Users\dell\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py, line 423, in execute
Python Executable: C:\Users\dell\AppData\Local\Programs\Python\Python39\python.exe
Python Version: 3.9.0
Python Path:
['C:\\Users\\dell\\Desktop\\greenaftech',
'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip',
'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39\\DLLs',
'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39\\lib',
'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39',
'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages',
'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\win32',
'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\win32\\lib',
'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\Pythonwin']
Server time: Sat, 30 Apr 2022 00:24:12 +0000
это мой views.py:
from django.shortcuts import render,redirect
from django.http import HttpResponse
from django.contrib.auth.models import User
from django.contrib import messages
# Create your views here.
def home(request):
return render(request,"website/index.html")
def signup(request):
if request.method=="POST":
username=request.POST.get('username')
password=request.POST.get('password')
email=request.POST.get('email')
myuser= User.objects.create_user(username,email,password)
myuser.save()
messages.success(request,"Your Account has been created.")
return redirect('signin')
return render(request,"website/signup.html")
def signin(request):
if request.method=='POST':
usern=request.POST.get('username')
passs=request.POST.get('password')
user=authenticate(username=usern,password=passs)
if user is not None:
login(request,user)
userr=user.username
return render(request,"website/index.html",{'username':userr})
else:
messages.error(request,"Wrong Infos")
return redirect('home')
return render(request,"website/signin.html")
def signout(request):
pass
и вот мои URLs.py :
from django.contrib import admin
from django.urls import path,include
from . import views
urlpatterns = [
path('',views.home,name='home'),
path('signup',views.signup,name='signup'),
path('signin',views.signin,name='signin'),
path('signout',views.signout,name='signout'),
]
Эта ошибка возникнет, если вы попытаетесь создать двух пользователей с одинаковым именем пользователя, при этом поле username вашей модели uath_user будет иметь ограничение unique=True (которое предотвращает появление двух записей с одинаковым значением в этом поле).
Обратите внимание, что если вы используете User.objects.create(...), а не User(username="username"...), то он автоматически сохранит новую запись, поэтому myUser.save() может пытаться повторить это создание, создавая проблему ограничения, но при этом позволяя вам видеть элемент в admin