在Django PostgreSQL中扩展auth_user字段及解决数据未存储问题
问题分析与解决方案
你的代码存在三个核心问题导致扩展字段无法保存、迁移无效:
User_Profile未与默认User模型建立关联,且创建实例后未执行保存操作- 表单
save方法错误地给User模型添加不存在的字段 - 未确保应用已注册到项目配置中
以下是分步修复方案:
1. 修复用户扩展模型(models.py)
给User_Profile添加与User的一对一关联,避免重复存储已有字段:
from django.db import models from django.contrib.auth.models import User class User_Profile(models.Model): # 与默认User模型建立一对一关联,用户删除时自动删除Profile user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') picture_url = models.CharField(max_length=120, default="") about = models.CharField(max_length=250, default="", blank=True) phone_num = models.CharField(max_length=15, default="", blank=True)
2. 修复注册表单(forms.py)
移除对User模型的非法字段赋值,改为在保存用户后自动创建关联的User_Profile:
from django.forms import * from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import User_Profile class Register_User_Form(UserCreationForm): username = CharField(label="Username", max_length=36) email = CharField(label="Email", max_length=120, widget=EmailInput()) password1 = CharField(label="Password", max_length=36, widget=PasswordInput()) password2 = CharField(label="Confirm Password", max_length=36, widget=PasswordInput()) phone_num = CharField(label="Phone Number (optional)", max_length=15, widget=NumberInput(), required=False) about = CharField(label="About you! (optional)", max_length=300, required=False) picture_url = CharField(label="Profile Photo URL (optional)", max_length=200, required=False) class Meta: model = User fields = ("username", "email", "password1", "password2", "phone_num", "about", "picture_url") def save(self, commit=True): # 先保存基础User对象 user = super().save(commit=commit) # 关联创建User_Profile if commit: User_Profile.objects.create( user=user, phone_num=self.cleaned_data["phone_num"], about=self.cleaned_data["about"], picture_url=self.cleaned_data["picture_url"] ) return user
3. 修复注册视图(views.py)
移除手动创建User_Profile的冗余代码,直接使用表单返回的用户对象:
from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.contrib import messages from profiles.forms import Register_User_Form def register_user(request): if request.method == 'POST': form = Register_User_Form(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data["username"] password = form.cleaned_data["password1"] user = authenticate(username=username, password=password) login(request, user) messages.success(request, "Registration Successful") return redirect('/') else: form = Register_User_Form() return render(request, 'registration/register.html', {"form": form})
4. 确保应用已注册
在项目settings.py的INSTALLED_APPS中添加你的profiles应用:
INSTALLED_APPS = [ # 其他默认应用 'profiles', ]
5. 执行数据库迁移
运行以下命令生成并应用迁移,创建User_Profile表:
python manage.py makemigrations profiles python manage.py migrate
内容的提问来源于stack exchange,提问作者Berk Efe Keskin
相关产品推荐
相关产品推荐

