Git Репо
Я новичок в Django. Я пытался реализовать JWT внутри Python, но когда я добавляю нового пользователя, я получаю ошибку, которая выглядит следующим образом.
django .db.utils.OperationalError: таблица sampleapp_userprofile не имеет столбца с именем email
Я создал поле электронной почты и также поместил значение по умолчанию в поле электронной почты, и я все еще получаю эту ошибку. Я предоставил репозиторий git и приведенный ниже код, пожалуйста, помогите.
models.py
from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
# Create your models here.
class MyAccountManager(BaseUserManager):
def create_user(self, email, username, password=None):
if not email:
raise ValueError('Users must have an email address')
if not username:
raise ValueError('Users must have a username')
user = self.model(
email=self.normalize_email(email),
username=username,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, password):
user = self.create_user(
email=self.normalize_email(email),
password=password,
username=username,
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class UserProfile(AbstractBaseUser):
email = models.EmailField(verbose_name="email",max_length=60, unique=True,default='')
username = models.CharField(max_length=30,default='Null')
password = models.CharField(verbose_name='password',max_length=16)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
objects = MyAccountManager()
USERNAME_FIELD = 'username'
EmailField = 'email'
REQUIRED_FIELDS = ['username']
def __str__(self):
return self.email
views.py
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status, generics
from rest_framework_simplejwt.views import TokenObtainPairView
from .serializers import *
from rest_framework.decorators import api_view
# Create your views here.
class LoginView(TokenObtainPairView):
"""
Login View with jWt token authentication
"""
serializer_class = MyTokenObtainPairSerializer
class registrationView(APIView):
def post(self,request,format=None):
if request.method == 'POST':
serializer = RegistrationSerializer(data=request.data)
data = {}
if serializer.is_valid():
account = serializer.save()
data['response'] = 'successfully registered new user.'
else:
data = serializer.errors
return Response(data)
serializers.py
from rest_framework import serializers, status
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from .models import UserProfile
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView
class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
def validate(self, attrs):
print('in')
user = authenticate(username=attrs['username'], password=attrs['password'])
if user is not None:
if user.is_active:
data = super().validate(attrs)
refresh = self.get_token(self.user)
refresh['username'] = self.user.username
try:
obj = UserProfile.objects.get(user=self.user)
refresh['employeeRole'] = obj.employeeRole
data["refresh"] = str(refresh)
data["access"] = str(refresh.access_token)
data["employee_id"] = self.user.id
data['user_name']= self.user.username
data["employeeRole"] = obj.employeeRole
data['first_name']= self.user.first_name
data['last_name']= self.user.last_name
except Exception as e:
raise serializers.ValidationError('Something Wrong!')
return data
else:
raise serializers.ValidationError('Account is Blocked')
else:
raise serializers.ValidationError('Incorrect userid/email and password combination!')
class RegistrationSerializer(serializers.ModelSerializer):
email = serializers.EmailField(style={'input_type': 'email'})
username = serializers.CharField(min_length=1)
class Meta:
model = UserProfile
fields = ['email','username', 'password']
extra_kwargs = {
'password': {'write_only': True,'min_length':8},
}
def save(self):
account = UserProfile(
email=self.validated_data['email'],
username=self.validated_data['username'],
password=self.validated_data['password']
)
account.save()
return account