我正在尝试通过从Django的内置User模型扩展它来创建模型UserProfile。填写表格后,数据应保存在UserProfile模型中。只是没有发生
最初,数据仅保存在User模型中,而不保存在UserProfile模型中。我从网上申请了一些推荐的解决方案,但现在我什至无法填写表格。在提示注册时,我收到一条错误消息,
类型对象“ UserProfile”没有属性“ USERNAME_FIELD”
#models.py
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
email = models.EmailField( max_length=254)
country = models.CharField( max_length=50)
#forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import UserProfile
class RegistrationForm(UserCreationForm):
class Meta:
model = UserProfile
fields = ['email', 'country']
#views.py
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .forms import RegistrationForm
from .models import UserProfile
from django.contrib.auth.models import User
def home(request):
return render(request , 'guide/index.html')
def register(request):
if request.method=='POST':
form = RegistrationForm(request.POST)
if form.is_valid():
u= form.save(commit=False)
u.user = request.user
u.save()
return redirect('home')
else:
form=RegistrationForm()
return render(request, 'guide/register.html', {'form':form})
我希望代码运行并将数据保存到UserProfile模型,但是页面上说UserProfile没有属性'USERNAME_FIELD'