在 django 中将自定义字段添加到 auth_user 表

Posted

技术标签:

【中文标题】在 django 中将自定义字段添加到 auth_user 表【英文标题】:Add Custom Field to auth_user table in django 【发布时间】:2013-10-19 07:29:52 【问题描述】:

我想将我的自定义 TrustAdministration 字段添加到 django 中的 Auth_User 表中

这是我的 Model.py

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

class Trust(models.Model):
    name = models.CharField(max_length=200)

class TrustAdministration(models.Model):
        user = models.OneToOneField(User)
        full_name = models.CharField(max_length=200)
        email = moels.CharField(max_length=75)

form.py

from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from models import Trust, TrustAdministration

class TrustForm(form.ModelForm):
    class Meta():
        model = Trust

class TrustAdministration(forms.ModelForm):
    class Meta():
        model = TrustAdministration

class UserCreateForm(UserCreationForm):
    class Meta():
        model = User

view.py

def trust_registration(request):
    if request.POST:
        trust_form = TrustForm(request.POST, instance=Trust())
        trust_admin_form = TrustAdministrationForm(request.POST,instance=TrustAdministration())
        user_form = UserCreateForm(request.POST)
        if trust_form.is_valid() and trust_admin_form.is_valid() and user_form.is_valid():
            username = request.POST['username']
            password = request.POST['password']
            new_user = User.objects.create_user(username=username, password=password)   
            new_user.save()
            new_trust = trust_form.save()
            new_trust_admin = trust_admin_form.save(commit = False)
            new_trust_admin.trust = new_trust
            new_trust_admin.user = new_user
            new_trust_admin.email = username
            new_trust_admin.save()
        else:
            return HttpResponseRedirect('/registration/trust_registration')
        return HttpResponseRedirect('/registration/trust_details')
    else:
        trust_form = TrustForm()
        trust_admin_form = TrustAdministrationForm()
        user_form = UserCreateForm()

    return render(request, 'trust/trust_registration.html', 'trust_form': trust_form,
                                                        'trust_admin_form' : trust_admin_form,
                                                        'user_form' : user_form)   

当我提交表单时出现错误需要密码,但用户创建表单在表单上显示密码1 和密码2 的文本字段。

并告诉我为 TrustAdministration 模型创建用户条目的方法是对还是错。

【问题讨论】:

【参考方案1】:

你有:

email = moels.CharField(max_length=75)

看起来你只是拼错了模型:

email = models.CharField(max_length=75)

【讨论】:

以上是关于在 django 中将自定义字段添加到 auth_user 表的主要内容,如果未能解决你的问题,请参考以下文章

django-rest-auth 自定义注册无法保存额外字段

如何在 DRF + django-rest-auth 中使用自定义用户模型保存注册时的额外字段

Django自定义Auth模块方式

Django自定义Auth模块方式

django 自定义User

Magento在admin中将自定义输入字段添加到客户帐户窗体