Python 在django用户模型和自定义用户模型中保存新用户
无法将用户保存到内置的auth_user django模型和我的自定义用户模型。我的代码将用户保存到django模型,但不保存到我的帐户模型 models.pyPython 在django用户模型和自定义用户模型中保存新用户,python,django,django-models,django-users,Python,Django,Django Models,Django Users,无法将用户保存到内置的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_l
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' )
和视图.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)
})
这是我一直遵循的指南:
编辑:
经过一些更改(我更新了上面的代码),现在我在account表中获得了用户id,但属性没有。所以我猜这和我的注册方法有关。你放在文件夹:
静态/myAccount/register.html
我需要你的路径?你放在文件夹:
静态/myAccount/register.html
我需要你的路径?myAccount/register.html位于我的templates文件夹中。我的路径如下所示:myAccount/register.html位于我的模板文件夹中。我的路径是这样的:这回答了我的问题。这回答了我的问题。
return render(request, 'myAccount/register.html', {'form': form})