django模型表单将数据保存到多个模型

时间:2020-05-22 13:03:03

标签: python django

我有一个带有团队字段的“自定义用户”模型。我还为自定义用户提供了一个带有ManyToManyField的团队模型。

我有一个模板,允许用户使用他们想要的任何团队名称来创建团队。创建后,我希望分配该用户的团队,但是直到创建团队后才创建团队主键,那么如何将该主键ID放入“自定义用户”模型中?

我的想法是,在视图中保存“创建团队”表单后,我将执行用户保存,但是我不确定该怎么做。

models.py

class Team(models.Model):
    team_id = models.BigAutoField(auto_created=True, primary_key=True)
    team_name = models.CharField(max_length=35, null=False, default='YourTeam')
    team_type = models.CharField(choices=MEMBERSHIP_CHOICES, default='Free', max_length=30)
    num_users = models.IntegerField(default=1)
    emails = models.ManyToManyField('CustomUser', related_name='teamemails')

class CustomUser(AbstractUser):
    username = None
    first_name = models.CharField(max_length=255, unique=False, verbose_name='first name')
    last_name = models.CharField(max_length=255, unique=False, verbose_name='last name')
    email = models.EmailField(max_length=255, unique=True)
    team = models.ForeignKey(Team, on_delete=models.SET_NULL, null=True, blank=True, related_name='userteam')
    team_leader = models.BooleanField(default=False)
    team_member = models.BooleanField(default=False)

forms.py

class CreateTeamForm(forms.ModelForm):
    team_name = forms.CharField(label='Team Name', required=True)

    class Meta:
        model = Team
        fields = ['team_name']

views.py

@verified_email_required
def create_team(request):
    template = 'users/create_team.html'

    if request.method == "POST":
        form = CreateTeamForm(request.POST)

        if form.is_valid():
            form = form.save(commit=False)
            form.team_name = request.team_name
            form.save()
            messages.success(request, 'Team Created!')
            return redirect('home')
        else:
            messages.error(request, 'Oops! Something went wrong')

    else:

        form = CreateTeamForm()
    context = {
        'form':form,
    }
    return render(request, template, context)

0 个答案:

没有答案