Я сделал функцию otp_code в django и не знаю, как ее отладить; она выдает такую ошибку (('QuerySet' object has no attribute 'created_at')) [дубликат]
когда я ввожу otp_code, полученный из определения create_otp_code, он должен показать мне сообщение об успехе, но он возвращает следующую ошибку я выделил строку ошибки в views.py
Вы можете найти django-коды приложения здесь, ниже
view.py
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from account.forms import CustomUserCreationForm, SignInForm
import random
from django.utils import timezone
from datetime import timedelta
from django.contrib import messages
from .models import *
# Create your views here.
def signup(request):
global form
if request.method == 'POST':
form = CustomUserCreationForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
return redirect('success_massage')
else:
form = CustomUserCreationForm()
return render(request, 'account/signup.html', {'form': form})
def signin(request):
if request.method == 'POST':
getting_in = SignInForm(request.POST)
if getting_in.is_valid():
cd = getting_in.cleaned_data
user = authenticate(username=cd['username'], password=cd['password'])
if user is not None:
login(request, user)
return redirect('success_massage')
else:
getting_in = SignInForm()
return render(request, 'account/signin.html', {'form': getting_in})
@login_required
def change_password(request):
if request.method == 'POST':
user = request.user
password = request.POST.get('password')
confirm_password = request.POST.get('confirm_password')
if password == confirm_password:
user.set_password(password)
user.save()
return redirect('success_massage')
return render(request, 'change_password.html', {'form': change_password})
@login_required
def create_otp_code(request):
if request.method == 'POST':
code = random.randint(1000, 9999)
OtpCode.objects.create(user=request.user, code=code)
return redirect('enter_otp_code')
return render(request, 'account/create_otp_code.html')
@login_required
def enter_otp_code(request):
if request.method == 'POST':
code = request.POST.get('otp_code')
otp_object = OtpCode.objects.filter(user=request.user, code=code)
if otp_object:
**if timezone.now() - otp_object.created_at <= timedelta(minutes=5):**
request.user.is_active = True
request.user.save()
otp_object.delete()
return redirect('success_massage')
else:
otp_object.delete()
messages.error(request, 'OTP code expired')
else:
messages.error(request, 'OTP code not found')
return render(request, 'enter_otp_code.html')
urls.py
from django.urls import path
from .views import *
urlpatterns = [
path('signup/', signup, name='signup'),
path('signin/', signin, name='login'),
path('change_password/', change_password, name='change_password'),
path('create_otp_code', create_otp_code),
path('enter_otp_code/', enter_otp_code,name='enter_otp_code'),
]
models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from .managers import *
from random import randint
# Create your models here.
class User(AbstractBaseUser):
email = models.EmailField(unique=True)
phone_number = models.CharField(max_length=11, unique=True)
joined = models.DateTimeField(auto_now_add=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'phone_number'
REQUIRED_FIELDS = ['email']
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_lable):
return True
def __str__(self):
return self.phone_number
class OtpCode(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
code = models.IntegerField()
created_at = models.DateTimeField(auto_now_add=True)
managers.py
from django.contrib.auth.models import BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, email, phone_number, password=None, ):
if not email:
raise ValueError('Users must have an email address')
if not phone_number:
raise ValueError('Users must have an phone number')
email = self.normalize_email(email)
user = self.model(email=email, phone_number=phone_number, password=password)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, phone_number, password):
if not phone_number:
raise ValueError('Users must have an password')
email = self.normalize_email(email)
user = self.model(email=email, phone_number=phone_number, password=password)
user.is_staff = True
user.is_superuser = True
user.is_active = True
user.set_password(password)
user.save(using=self._db)
return user
app.py
from django.apps import AppConfig
class AccountConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'account'
Я переместил базу данных... Я использовал предложения по отладке от pycharm, однако я не знаю, что попробовать