在firsttime save()从User模型获取OneToOneField数据

时间:2017-03-19 06:40:29

标签: python django django-forms

我想扩展我的用户模型并在其他模型中添加字段

我希望它一次保存两个表单

每个表单都可以正常运行但是 问题是当我把它们结合起来时 我无法从用户模型中获取用户名

class Information(models.Model):
    Username = models.OneToOneField(User, on_delete=models.CASCADE)

我试过这个views.py

RegisterForm = self.form_class(request.POST)
InfoForm = self.second_form_class(request.POST)

if RegisterForm.is_valid() and InfoForm.is_valid():
    username = request.POST.get('username')
    password = request.POST.get('password')
    email = request.POST.get('email')
    first_name = request.POST.get('first_name')
    last_name = request.POST.get('last_name')

    User_obj = User(username=username, password=password, email=email, first_name=first_name,
                        last_name=last_name)
    user = User_obj.save()

    Username = username 
    PhoneNo = request.POST.get('PhoneNo')
    Address = request.POST.get('Address')
    Country = request.POST.get('Country')
    Info_obj = Information(Username=Username , PhoneNo=PhoneNo, Address=Address, Country=Country)
    Info_obj.save()

forms.py

class RegisterForm(forms.ModelForm):
    username = forms.CharField(max_length=40)
    password = forms.CharField(widget=forms.PasswordInput())

    class Meta:
        model = User
        fields = ["username","password", "email", "first_name", "last_name"]


class InfoForm(forms.ModelForm):
    Username = forms.CharField(max_length=40, required=False)

    class Meta:
        model = Information
        fields = ["Username","PhoneNo","Address","Country"]

我在这里想念一下吗? 它可以保存给用户,但它不会保存到信息模型

我认为问题在于InfoForm上的用户名

1 个答案:

答案 0 :(得分:1)

问题在于InfoForm的用户名字段

而不是直接从RegisterForm中获取值

username = request.POST.get('username')

# with this code below Django demands that i need username instance from User model
Username = username 

所以在保存RegisterForm之后,我使用objects.get()方法从用户数据库中获取值

Username = User.objects.get(username=username)

解决方案

RegisterForm = self.form_class(request.POST)
InfoForm = self.second_form_class(request.POST)

if RegisterForm.is_valid() and InfoForm.is_valid():
    username = request.POST.get('username')
    password = request.POST.get('password')
    email = request.POST.get('email')
    first_name = request.POST.get('first_name')
    last_name = request.POST.get('last_name')

    User_obj = User(username=username, password=password, email=email, first_name=first_name,
                        last_name=last_name)
    User_obj.save()

    # i call the username from the User database after saving them
    Username = User.objects.get(username=username)
    PhoneNo = request.POST.get('PhoneNo')
    Address = request.POST.get('Address')
    Country = request.POST.get('Country')
    Info_obj = Information(Username=Username , PhoneNo=PhoneNo, Address=Address, Country=Country)
    Info_obj.save()

不知道我是否正确解释了

干杯