Я не могу создать пользователей в моем приложении django через форму регистрации, которую я создал
Я могу создавать пользователей через оболочку manage.py, но не через форму регистрации, когда я нажимаю кнопку отправки, она просто перезагружает страницу и больше ничего не происходит, также, мой vs код подчеркивает функцию create_user в строке "user = Account.objects.create_user(...", он говорит "Cannot access attribute "create_user" for class "BaseManager[Account]""
Это мой файл forms.py:
from django import forms from .models import Account
class RegistrationForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput(attrs={ 'placeholder': 'Enter Password', })) ` confirm_password = forms.CharField(widget=forms.PasswordInput(attrs={ 'placeholder': 'Confirm Password', }))
email = forms.EmailField(
max_length=255, help_text="Required. Add a valid email address.")
document = forms.CharField(widget=forms.TextInput(attrs={
'placeholder': '(CPF/RG/PASSPORT)',
}), max_length=15, help_text="Enter a valid CPF, RG, or Passport.")
address = forms.CharField(widget=forms.TextInput(attrs={
'placeholder': '1337 Example St, FL, US',
}), max_length=255, help_text="Enter your address.")
class Meta:
model = Account
fields = ['first_name', 'last_name',
'username', 'phone_number', 'email', 'address', 'document', 'password']
def __init__(self, *args, **kwargs):
super(RegistrationForm, self).__init__(*args, **kwargs)
self.fields['phone_number'].widget.attrs['placeholder'] = '(xx) x xxxx-xxxx'
for field in self.fields:
self.fields[field].widget.attrs['class'] = 'form-control'`
Это мой models.py
from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
class MyAccountManager(BaseUserManager):
def create_user(self, first_name, last_name, document, phone_number, email, username, address=None, password=None, TCM_wallet=0):
if not email:
raise ValueError('User must have an email address.')
if not username:
raise ValueError('User must have a username.')
if not document:
raise ValueError('User must provide the document.')
if not address:
raise ValueError('User must provide the address.')
user = self.model(
email=self.normalize_email(email),
username=username,
first_name=first_name,
last_name=last_name,
phone_number=phone_number,
document=document,
address=address,
TCM_wallet=TCM_wallet,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, first_name, last_name, username, phone_number, document, email, password, address, TCM_wallet=0):
user = self.create_user(
email=self.normalize_email(email),
username=username,
first_name=first_name,
last_name=last_name,
document=document,
phone_number=phone_number,
address=address,
password=password,
TCM_wallet=TCM_wallet,
)
user.is_admin = True
user.is_active = True
user.is_staff = True
user.is_superadmin = True
user.save(using=self._db)
return user
class Account(AbstractBaseUser):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
username = models.CharField(max_length=50, unique=True)
email = models.EmailField(max_length=100, unique=True)
phone_number = models.CharField(max_length=50, blank=True)
document = models.CharField( max_length=15, unique=True, help_text='Required. Enter a valid document (CPF, RG, or Passport).')
address = models.CharField(max_length=100, blank=True, null=True)
TCM_wallet = models.FloatField(default=0, editable=True)
# required fields
date_joined = models.DateTimeField(auto_now_add=True)
last_login = models.DateTimeField(auto_now=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_superadmin = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'first_name',
'last_name', 'document', 'address', 'phone_number',]
objects = MyAccountManager()
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True`
... а это мой views.py:
from django.shortcuts import render, redirect from .forms import RegistrationForm from .models import Account
def register(request):
if request.method == 'POST': form = RegistrationForm(request.POST)
if form.is_valid():
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
email = form.cleaned_data['email']
phone_number = form.cleaned_data['phone_number']
document = form.cleaned_data['document']
address = form.cleaned_data['address']
password = form.cleaned_data['password']
username = email.split('@')[0]
user = Account.objects.create_user(
first_name=first_name,
last_name=last_name,
email=email,
document=document,
address=address,
password=password,
username=username,
)
user.phone_number = phone_number
user.save()
else:
form = RegistrationForm()
context = {
'form': form,
}
return render(request, 'accounts/register.html', context)
def login(request): return render(request, 'accounts/login.html')
def logout(request): # assuming 'login' is the name of your login url pattern return redirect('login')`
Может ли кто-нибудь помочь мне понять этот вопрос? Спасибо.
Я ожидал, что информация, содержащаяся в форме регистрации пользователя, будет собрана и сохранена как user.save().