Django手动保存用户个人资料

时间:2017-07-25 08:33:10

标签: python django

我创建了一个Profile并使用OneToOneField附加到用户模型。我有一个注册表单,用户输入与用户和个人资料相对应的输入。 Django提供User.objects.create_user来保存与User模型相关的字段,但我不知道如何手动保存Profile模型的详细信息。
这是我的代码:

models.py

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

def Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    full_name = models.CharField(max_length=150, required=True)
    # lot more fields here  

views.py

@csrf_protect
def register(request):
    if request.method == 'POST':
        full_name = request.POST.get('full_name', '')
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        User.objects.create_user(username=username, password=password)
        # how to save Profile full_name here

    return render(request, 'register.html')  

register.html

<form method="post" action="/register/">{% csrf_token %}
    <div class="form-group">
        <label for="full_name">Name</label>
        <input type="text" name="full_name" id="full_name">
    </div>  
    <div class="form-group">
        <label for="username">Username</label>
        <input type="text" name="username" value="" id="username">
    </div>
    <div class="form">
        <label for="password">Password</label>
        <input type="pass" name="password" value="" id="password">
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>  

1)如何在full_name中保存Profile views.py模型?我是否可以在不为每个想要保存或信号的模型创建表单类的情况下执行此操作? 2)我是否需要在settings.py中更改auth_user_model才能手动保存个人资料详情?
3)如何在不创建新Form类的情况下验证字段?

1 个答案:

答案 0 :(得分:3)

@csrf_protect
def register(request):
    if request.method == 'POST':
        full_name = request.POST.get('full_name', '')
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        user = User.objects.create_user(username=username, password=password)
        Profile.objects.create(user=user,full_name=full_name)
        # how to save Profile full_name here

    return render(request, 'register.html')  

您可以使用创建的用户实例创建与该用户关联的配置文件