如何关联以相同形式保存的两个Django模型 [英] How to relate two django models that are saved by the same form

查看:55
本文介绍了如何关联以相同形式保存的两个Django模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在新项目的前面,我有一个可以修改2个Django模型的表单。实际上,用户必须输入他的电子邮件,姓名,个人目标和该目标的期限。 电子邮件和名称属于模型用户,而其他两个属于模型目标。

on the frontsite of my new project I have a form that modifies 2 Django models. In fact, the user has to enter his email, name, a personal goal and a deadline for that goal. "email" and "name" belong to the model "User" while the other two belong to the model "Goal".

我正在尝试为目标与目标建立联系(ForeignKey)属于用户,但我做不到。我知道如果已经存在一个用户,但在我的情况下该用户和目标(属于他)是同时创建的。

I am trying to give the Goal a relation(ForeignKey) to belong to the user but I am unable to do it. I know how to do it if there is a user already existing but in my situation the user and the goal(that belongs to him) are created at the same time.

我的视图如下所示:

from django.shortcuts import render
from .models import Goal, User
from .forms import GoalForm, UserForm


def front_site(request):
    if request.method == "POST":
        goal_form = GoalForm(request.POST)
        user_form = UserForm(request.POST)
        if all([goal_form.is_valid(), user_form.is_valid()]):
            user_form.save()
            goal_form.save()
            return render(request, 'goalapp/single_goal.html',  {'user_form': user_form, 'goal_form': goal_form})
        else:
            user_form = UserForm(request.POST)
            goal_form = GoalForm(request.POST)
            return render(request, 'goalapp/front_site.html',  {'user_form': user_form, 'goal_form': goal_form})
    else:
        goal_form = GoalForm()
        user_form = UserForm()
        return render(request, 'goalapp/front_site.html',  {'user_form': user_form, 'goal_form': goal_form})

我的模型如下:

from django.db import models
from django.utils import timezone

class User(models.Model):
    user = models.CharField(max_length=50)
    user_email = models.EmailField()

    def __str__(self):
        return self.user

class Goal(models.Model):
    user = models.ForeignKey('goalapp.User', related_name='goal',    on_delete=models.CASCADE, null=True)
    goal_body = models.CharField(max_length= 100)
    goal_deadline = models.DateTimeField(default=timezone.now)
    goal_status = models.IntegerField(default = 1)

    def __str__(self):
        return self.goal_body

如何获取此信息

推荐答案

您可以通过使用commit = False保存表单来获取目标实例。

You can get the goal instance by saving the form with commit=False.

user = user_form.save()
goal = goal_form.save(commit=False)
goal.user = user
goal.save()

这篇关于如何关联以相同形式保存的两个Django模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆