Django用户配置文件模型注册表单

我正在开发django项目 .

现在我正在使用 Profiles 模型进行注册表单 .

但我遇到了问题 .

models.py:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    usernickname = models.CharField(db_column='userNickName', max_length=50, blank=True, null=True)
    userbirth = models.DateField(db_column='userBirth', blank=True, null=True)  

    class Meta:
        managed = False
        db_table = 'profile'

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    print(instance)
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

forms.py:

from django import forms
from django.contrib.auth.models import User

class UserForm(forms.ModelForm):
    userBirth = forms.DateField()

    class Meta:
        model = User
        fields = ('username', 'password', 'userBirth')
        widgets = {
            'username': forms.TextInput(),
            'password': forms.PasswordInput(),
            'userBirth': forms.DateField(),
        }

views.py:

def join(request):
    if request.method == "POST":
        userForm = UserForm(request.POST, prefix='user')
        profileForm = ProfileForm(request.POST, prefix='profile')
        if userForm.is_valid() * profileForm.is_valid():
            user = userForm.save()
            profile = profileForm.save(commit=False)
            profile.user = user
            profile.save()

            return redirect('index')
    else:
        userForm = UserForm()
        profileForm = ProfileForm()
    return render_to_response('registration/join.html',dict(userform=userForm,
                                                profileform=profileForm))

当注册时,

/ join /的内部错误(1054,“字段列表'中的未知列'profile.user_id'”)

此错误返回 .

登录/ admin时,返回相同的错误 . 我什么都不知道..

我引用了这个博客:

https://simpleisbetterthancomplex.com/tutorial/2017/02/18/how-to-create-user-sign-up-view.html#sign-up-with-profile-model

回答(1)

3 years ago

如果您已有模型配置文件 - 则添加

用户字段上的db_column = $

如果没有 - 在Meta中设置managed = True .

此外,您可以使用related_name ='profile'从用户获取配置文件实例 .

Django尝试通过user_id列接受配置文件实例,但无法识别它 .