Возникли проблемы с сохранением пользователя во встроенной модели auth_user django и моей пользовательской модели. Мой код сохраняет пользователя в модели django, но не в модели моей учетной записи.
models.py
class Account(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
address = models.CharField(max_length=10)
addressNumber = models.CharField(max_length=20)
accountImage = models.CharField(max_length=999)
def create_user_profile(sender, instance, created, **kwargs):
if created:
profile, created =
Account.objects.get_or_create(user=instance)
post_save.connect(create_user_profile, sender=User)
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignUpForm(UserCreationForm):
address = forms.CharField(max_length=255)
addressNumber = forms.CharField(max_length=255)
image = forms.CharField(max_length=255)
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email',
'password1', 'password2', 'address', 'addressNumber', 'image' )
и views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
from myAccount.forms.userForm import AccountForm
from myAccount.models import Account
from myAccount.forms.forms import SignUpForm
def register(request):
form = SignUpForm(data=request.POST)
if request.method == 'POST':
if form.is_valid():
account = form.save()
account.refresh_from_db() # load the profile instance created by the signal
account.address = form.cleaned_data.get('address')
account.addressNumber = form.cleaned_data.get('addressNumber')
account.addressImage = form.cleaned_data.get('accountImage')
account.save()
raw_password = form.cleaned_data.get('password1')
return redirect('login')
return render(request, 'myAccount/register.html', {'form': form})
@login_required
def seePurchasehistory(request):
return render(request, 'myAccount/pruchaseHistory.html')
@login_required
def accountInfo(request):
account = Account.objects.filter(user=request.user).first()
if request.method == 'POST':
form = AccountForm(instance=AccountForm, data=request.POST)
if form.is_valid():
account = form.save(commit=False)
account.user = request.user
account.save()
return redirect('homepage-index')
return render(request, 'myAccount/accountInfo.html', {
'form': AccountForm(instance=account)
})
Это руководство, которым я следил: https://simpleisbetterthancomplex.com/tutorial/2017/02/18/how-to-create-user-sign-up-view.html
РЕДАКТИРОВАТЬ: с некоторыми изменениями (я обновил приведенный выше код) теперь я получаю идентификатор пользователя в своей таблице учетной записи, но атрибуты, которые я не делаю т. Полагаю, это как-то связано с моим методом регистрации.