Django - 尝试不在形式但在模型中的字段

时间:2017-12-07 23:18:45

标签: python django django-models django-forms django-views

现在我有一个带有一个字段的model.form,但该模型有3个字段(参见下面的参考资料),其中1个字段由表单设置,其中一个默认为false,因为它应该是最后一个我将在视图中设置但它不会正确地执行它并且为什么会这么做。

型号&形式。

class TeamMembership(models.Model):
    user = models.ForeignKey(User)
    team = models.ForeignKey(Team)
    leader = models.BooleanField(default=False)

class TeamSettings_acceptForm(forms.ModelForm):
    class Meta:
        model = TeamMembership
        fields = ('user',)

查看

@login_required
def teamsettings_accept_applications(request, team_pk):
    if request.method == 'POST':
        logged_in_user = get_object_or_404(User, pk=request.user.pk)
        requested_team = get_object_or_404(Team, pk=team_pk)
        for member in requested_team.teammembership_set.all().order_by('-leader'):
            if member.user.pk == request.user.pk and member.leader:
                formaccept = TeamSettings_acceptForm(request.POST)
                accepteduserid = formaccept.data['user']
                teamapplications = TeamApplication.objects.all().filter(from_user=accepteduserid).count()
                if teamapplications > 1:
                    messages.success(request, "Error")
                    return redirect('teamsettings_applications', team_pk=team_pk)
                else:
                    if formaccept.is_valid():
                        teamapplications = TeamApplication.objects.all().filter(from_user=accepteduserid)
                        teamapplications.update(accepted=True)
                        formaccept.team = requested_team.pk
                        formaccept.save()
                        messages.success(request, "User has now been added to your team!")
                        return redirect('teamsettings_applications', team_pk=team_pk)

它应该创建一个包含该数据的新行并更新其他数据。

我从Django获得的回报是

staff_teammembership.team_id may not be NULL

1 个答案:

答案 0 :(得分:0)

您尚未将模型表单处理为模型的实例。因此formaccept不知道这里有什么团队,因为它是TeamSettings_acceptForm的一个实例,它没有团队作为字段。要修复此更改,请输入is_valid代码:

if formaccept.is_valid():
    teamapplications = TeamApplication.objects.all().filter(from_user=accepteduserid)
    teamapplications.update(accepted=True)

    # New code here
    new_team_membership = formaccept.save(commit=false)
    new_team_membership.team = requested_team.pk
    new_team_membership.save()

    messages.success(request, "User has now been added to your team!")
    return redirect('teamsettings_applications', team_pk=team_pk)

使用commit = false对于Modelforms非常方便。