Django 中的外键 - 第二种形式

Foreign Key in Django - second Form

我有第二份表格,必须在第一份表格之后提交。 但是,我无法保存两个模型之间的关系,除非我为提交表格的人提供选项,为第一个选择电子邮件 form.My 的想法是直接在后端提供此信息,但我做不到。

我的模型太大了,无法 post 全部放在这里,所以如果有人能帮助我提供一个通用的想法,我将很高兴。

我在 Django 中以两种形式使用 ModelForm。

我的模特: 用户 人 志愿者 - 客户 - 员工

我有 3 种类型的志愿者:管理员;程序;委员会; 填完志愿者-个人-用户模型后,我需要转到下一个表格以获取志愿者管理或志愿者计划或志愿者委员会;

因为用户也使用电子邮件作为主键,这就是我从我的管理程序创建外键时的值,并且模型形式为我提供了电子邮件的选择。但是在数据库上,只保留id作为参考。

我处理第一种形式的第一个视图:

def volunteer_form(request):

if request.method == 'POST':
    form = VolunteerForm(request.POST)
    if form.is_valid():
        saving = form.save(commit=False)
        saving.password = make_password(form.cleaned_data['password'])
        saving.save()
        item = saving.id
        if saving.person_volunteer_type == 'Program':
            return HttpResponse('<script language="JavaScript"> location.href="http://127.0.0.1:8000/login/volunteer_program?id=' + str(item) + '" </script>')

        elif saving.person_volunteer_type == 'Admin"]':
            return HttpResponse('<script language="JavaScript"> alert("You have sucessful created a new Volunteer"); location.href="http://127.0.0.1:8000/login/clock_in/" </script>')

        elif saving.person_volunteer_type == 'Committee':
            return HttpResponse('<script language="JavaScript"> alert("You have sucessful created a new Volunteer"); location.href="http://127.0.0.1:8000/login/clock_in/" </script>')

else:
    form = VolunteerForm()

return render(request, 'loginPortal/volunteer_form.html', {'form' : form})

关于处理第二种形式:

def volunteer_program(request):
if request.method == 'POST':
    form = VolunteerProgramForm(request.POST)
    if form.is_valid():
        saving = form.save(commit=False)
        saving.pvolunteer_personid_id = form.cleaned_data.get('id_pvolunteer_personid_id')
        saving.save()
        return HttpResponse('<script language="JavaScript"> alert("You have sucessful created a new Volunteer"); location.href="http://127.0.0.1:8000/login/clock_in/" </script>')

elif request.method =='GET':
    item = request.GET['id']
    form = VolunteerProgramForm()

    return render(request, 'loginPortal/volunteer_program.html', {'form' : form , 'item' : item })

else:
    form = VolunteerProgramForm()

return render(request, 'loginPortal/volunteer_program.html', {'form' : form })

通用答案,假设您的第二个模型具有第一个模型的 ForeignKey。在您的视图 post:

中执行此操作

1) 验证第一个表单,如果无法验证,return 有错误。

2) 验证第二个表单,如果它不会验证,return 有错误。

3) 如果两者都通过,则保存第一种形式的实例:

first_instance = first_form.save()

4) 保存第二种形式的实例而不提交对数据库的更改:

second_instance = second_form.save(commit=False)

5) 更新第二个模型实例的外键:

second_instance.fk_to_first_model = first_instance

6) 将第二个实例保存到数据库

second_instance.save()

7) Return成功!