У меня есть существующая таблица Customer, и я создаю для нее модель
from django.contrib.auth.models import AbstractUser
class Customer(AbstractUser):
user_id = models.AutoField(primary_key=True)
username = models.CharField(max_length=100,unique=True)
password = models.CharField(max_length=32)
first_name=models.CharField(max_length=250)
last_name=models.CharField(max_length=250)
email=models.EmailField(max_length=250)
country=models.CharField(max_length=250)
city=models.CharField(max_length=250)
zip=models.CharField(max_length=250)
state=models.CharField(max_length=250)
territory=models.CharField(max_length=250)
phone=models.CharField(max_length=15)
address =models.TextField(blank = True)
profile_pic= models.ImageField(upload_to='media/image',default='')
notes = models.TextField(blank = True)
#date_added=models.DateField()
token=models.CharField(max_length=32)
is_active= EnumChoiceField(enum_class=ChoiceTypes , default=ChoiceTypes.active)
class Meta:
db_table="customer"
А также изменил модель пользователя по умолчанию в Settings.py
AUTH_USER_MODEL = 'Myapp.Customer'
Я вручную добавил last_login, is_superuser, is_active, is_staff, date_joined
столбцык таблице клиентов. Я создаю суперпользователя через командную строку, и данные были вставлены в таблицу Customer
. Но когда я проверяю API входа в систему, возникает странная ошибка
Снимок экрана почтальона
ВИД ВХОДА
from django.contrib.auth import authenticate
from django.views.decorators.csrf import csrf_exempt
from rest_framework.authtoken.models import Token
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.status import (
HTTP_400_BAD_REQUEST,
HTTP_404_NOT_FOUND,
HTTP_200_OK
)
from rest_framework.response import Response
from django.http import HttpResponse
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
def login(request):
username = request.data.get("username")
password = request.data.get("password")
if username is None or password is None:
return Response({'error': 'Please provide both username and password'}, status=HTTP_400_BAD_REQUEST)
user = authenticate(username=username, password=password)
if not user:
return Response({'error': 'Invalid Credentials'}, status=HTTP_404_NOT_FOUND)
token, _ = Token.objects.get_or_create(user=user)
return Response({'token': token.key}, status=HTTP_200_OK)
Traceback
Окружение:
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/
Django Version: 2.2.5
Python Version: 3.7.4
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'shoppingcart',
'rest_framework',
'rest_framework.authtoken']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Трассировка:
File "C:\Users\win7.system3\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\win7.system3\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "C:\Users\win7.system3\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\win7.system3\AppData\Local\Programs\Python\Python37\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
44. response = view_func(request, *args, **kwargs)
File "C:\Users\win7.system3\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\admin\sites.py" in login
399. return LoginView.as_view(**defaults)(request)
File "C:\Users\win7.system3\AppData\Local\Programs\Python\Python37\lib\site-packages\django\views\generic\base.py" in view
71. return self.dispatch(request, *args, **kwargs)
File "C:\Users\win7.system3\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\decorators.py" in _wrapper
45. return bound_method(*args, **kwargs)
File "C:\Users\win7.system3\AppData\Local\Programs\Python\Python37\lib\site-packages\django\views\decorators\debug.py" in sensitive_post_parameters_wrapper
76. return view(request, *args, **kwargs)
File "C:\Users\win7.system3\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\decorators.py" in _wrapper
45. return bound_method(*args, **kwargs)
File "C:\Users\win7.system3\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\decorators.py" in _wrapped_view
142. response = view_func(request, *args, **kwargs)
File "C:\Users\win7.system3\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\decorators.py" in _wrapper
45. return bound_method(*args, **kwargs)
File "C:\Users\win7.system3\AppData\Local\Programs\Python\Python37\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
44. response = view_func(request, *args, **kwargs)
File "C:\Users\win7.system3\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\views.py" in dispatch
61. return super().dispatch(request, *args, **kwargs)
File "C:\Users\win7.system3\AppData\Local\Programs\Python\Python37\lib\site-packages\django\views\generic\base.py" in dispatch
97. return handler(request, *args, **kwargs)
File "C:\Users\win7.system3\AppData\Local\Programs\Python\Python37\lib\site-packages\django\views\generic\edit.py" in post
141. if form.is_valid():
File "C:\Users\win7.system3\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\forms.py" in is_valid
185. return self.is_bound and not self.errors
File "C:\Users\win7.system3\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\forms.py" in errors
180. self.full_clean()
File "C:\Users\win7.system3\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\forms.py" in full_clean
382. self._clean_form()
File "C:\Users\win7.system3\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\forms.py" in _clean_form
409. cleaned_data = self.clean()
File "C:\Users\win7.system3\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\forms.py" in clean
196. self.user_cache = authenticate(self.request, username=username, password=password)
File "C:\Users\win7.system3\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\__init__.py" in authenticate
73. user = backend.authenticate(request, **credentials)
File "C:\Users\win7.system3\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\backends.py" in authenticate
26. if user.check_password(password) and self.user_can_authenticate(user):
File "C:\Users\win7.system3\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\base_user.py" in check_password
111. return check_password(raw_password, self.password, setter)
File "C:\Users\win7.system3\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\hashers.py" in check_password
50. must_update = hasher_changed or preferred.must_update(encoded)
File "C:\Users\win7.system3\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\hashers.py" in must_update
267. algorithm, iterations, salt, hash = encoded.split('$', 3)
Exception Type: ValueError at /admin/login/
Exception Value: not enough values to unpack (expected 4, got 3)
Также нельзя войти в систему для администратора. он показывает ту же ошибку, как показано ниже
вход на сайт
Я думаю, что таблицы созданы правильно и внешние ключи были настроены правильно ...
внешний ключ .. токен и таблица клиента ....
admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import Customer
admin.site.register(Customer, UserAdmin)