Django - 尝试使用不在表单中但在模型中的字段

Django - Trying to a field that is not in the form but is in the model

提问人:Melonendk 提问时间:12/8/2017 更新时间:12/8/2017 访问量:31

问:

现在我有一个 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
python django 表单 django 视图

评论


答:

0赞 Asher 12/8/2017 #1

您尚未将“模型”窗体处理为模型的实例。所以 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 非常方便。