-1

I have a ModelForm (EditGoalForm) which I use to edit an instance of a model (Goal). Some conditions must be met before saving form data. I used if statements to check these conditions and it still saves, instead of giving an error - like the if statement does nothing.

I have the following: 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})

After if form.is_valid, I checked if the authenticated user has the permission and if the goal_status field was not set to Done Goal. If both are True, then save. However, if I set the goal_status field to Done Goal, it still saves instead of displaying an error message. What could be wrong?

Caspian
  • 633
  • 1
  • 10
  • 29

1 Answers1

1

form.cleaned_data['goal_status'] is an instance of GoalStatus. It can never be equal to the string 'Goal Done' unless you either:

  • Implement __eq__ (and/or) __ne__:

    def __eq__(self, other):
        return self.status_name == other
    
  • Just compare what you really want to compare:

    form.cleaned_data['goal_status'].status_name != 'Done Goal'
    
DeepSpace
  • 78,697
  • 11
  • 109
  • 154