Задать вопрос
@Timurka200000

Не могу понять в чем ошибка:confirmation_code = ConfirmationCode(user=user, code=code)?

models.py:

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import User

class UserCreationForm(models.Model):
name = models.CharField('Имя', max_length=50)
surname = models.CharField('Фамилия', max_length=50)

def __str__(self):
return self.name

class Meta:
verbose_name = 'Ученики'
verbose_name_plural = 'Ученики'
class TableBase(models.Model):
name = models.CharField('Имя', max_length=50)
surname = models.CharField('Фамилия', max_length=50)

def __str__(self):
return self.name

class Meta:
verbose_name = 'Ученики'
verbose_name_plural = 'Ученики'


class User(AbstractUser):
pass

class Person(models.Model):
name = models.CharField(max_length=20)
age = models.IntegerField()
class User(models.Model):
name = models.CharField('Имя', max_length=50)
surname = models.CharField('Фамилия', max_length=50)

class ConfirmationCode(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
code = models.CharField(max_length=4)

def __str__(self):
return self.code

forms.py:

from django import forms
from django.contrib.auth.forms import UserCreationForm as BaseUserCreationForm
from django.contrib.auth.models import User
from django import forms

class UserCreationForm(BaseUserCreationForm):
class Meta:
model = User
fields = ('username', 'password1', 'password2')

class RegistrationForm(forms.ModelForm):
class Meta:
model = User
fields = ['username', 'password', 'email']

views.py:

import sqlite3
from django.views.generic import ListView
from django.contrib.auth.models import User
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth import authenticate, login
from .forms import RegistrationForm
from .models import ConfirmationCode
import secrets

def success_view(request):
return render(request, 'main/profil.html')

def enter_confirmation_code_view(request):
if request.method == 'POST':
entered_code = request.POST['code']
user = request.user
confirmation_code = ConfirmationCode(user=user, code=code)
if confirmation_code.code == entered_code:
user.is_active = True
user.save()
return redirect('success')
else:
# Код подтверждения неверный, показать сообщение об ошибке
return render(request, 'main/enter_confirmation_code.html', {'error_message': 'Неверный код подтверждения'})
else:
return render(request, 'main/enter_confirmation_code.html', {})

def registration_view(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
email = form.cleaned_data['email']
password = form.cleaned_data['password']
user = User.objects.create_user(username, email, password)
# Генерация уникального кода подтверждения
code = secrets.token_urlsafe(8)
confirmation_code = ConfirmationCode(user=user, code=code)
confirmation_code.save()

send_mail(
'Код подтверждения регистрации',
f'Ваш код подтверждения: {code}',
settings.EMAIL_HOST_USER,
[email],
fail_silently=False,
)
return redirect('/enter_confirmation_code/')
else:
form = RegistrationForm()
return render(request, 'main/registration.html', {'form': form})
Сами ошибки выглядят так:
ValueError: Cannot assign "": "ConfirmationCode.user" must be a "User" instance
причем в бд пользователь сохраняется

ValueError at /register/
Cannot assign "": "ConfirmationCode.user" must be a "User" instance.

line 42, in registration_view
confirmation_code = ConfirmationCode(user=user, code=code)
  • Вопрос задан
  • 58 просмотров
Подписаться 1 Средний 1 комментарий
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы
19 дек. 2024, в 02:11
15000 руб./за проект
19 дек. 2024, в 02:09
11000 руб./за проект
19 дек. 2024, в 00:46
30000 руб./за проект