-1

我有一个 ModelForm ( EditGoalForm),我用它来编辑模型 ( Goal) 的实例。在保存表单数据之前必须满足一些条件。我使用 if 语句来检查这些条件,它仍然保存,而不是给出错误 - 就像 if 语句什么都不做。

我有以下内容: models.py

class Goal(models.Model):
    goal_name = models.CharField(max_length=250)
    goal_status = models.ForeignKey(GoalStatus, on_delete=models.CASCADE, related_name='goal_status')
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='scrumy_goal_user')

class GoalStatus(models.Model):
    status_name = models.CharField(max_length=250)

forms.py

class EditGoalForm(forms.ModelForm):
    goal_status = forms.ModelChoiceField(queryset=GoalStatus.objects.all(), empty_label="Select Goal Status")

    class Meta:
        model = Goal
        fields = ('goal_status',)

views.py

def move_goal(request, goal_id):
    goal_instance = Goal.objects.get(goal_id=goal_id)

    ERROR_MESSAGE = '''BlahBlahBlah'''

    has_perm_cannot_move_to_done = request.user.has_perm('application.cannot_move_to_done')
    has_perm_can_move_goal_anywhere = request.user.has_perm('application.can_move_goal_anywhere')
    has_perm_can_move_someones_goal_from_verify_to_done = request.user.has_perm('application.can_move_someones_goal_from_verify_to_done')
    has_perm_can_move_anybodys_goal_to_any_column = request.user.has_perm('application.can_move_anybodys_goal_to_any_column')

    if request.method == 'POST':
        form = EditGoalForm(request.POST, instance=goal_instance)
        if form.is_valid():
            if (has_perm_cannot_move_to_done and form.cleaned_data['goal_status'] != 'Done Goal'):
                form.save()
                messages.success(request, 'Goal Update Successful')
                return redirect('home')
            else:
                messages.error(request, ERROR_MESSAGE)
    else:
        form = EditGoalForm(instance=goal_instance)
    return render(request, 'move_goal.html', {'form': form})

之后if form.is_valid,我检查了经过身份验证的用户是否具有权限以及该goal_status字段是否未设置为Done Goal. 如果两者都为真,则保存。但是,如果我将该goal_status字段设置为Done Goal,它仍然会保存而不是显示错误消息。有什么问题?

4

1 回答 1

1

form.cleaned_data['goal_status']是 的一个实例GoalStatus。它永远不能等于字符串'Goal Done',除非您:

  • 实施__eq__(和/或)__ne__

    def __eq__(self, other):
        return self.status_name == other
    
  • 只需比较您真正想要比较的内容:

    form.cleaned_data['goal_status'].status_name != 'Done Goal'
    
于 2019-08-01T12:42:42.287 回答