Django-在某些条件下处理表格

时间:2019-07-28 18:36:06

标签: python-3.x django-models django-forms django-views django-2.2

在某些情况下,我试图编写一个视图来编辑ModelForm的实例。我需要帮助来整理条件。用户可以属于四个组:AdminDeveloperOwnerQuality Assurance。数据库中有四个GoalStatus模型实例:每周目标,每日目标,验证目标,完成目标。现在的条件:

  • “开发者”组中经过身份验证的用户可以将其Goal_status更新为“每周”,“每日”或“验证目标”,但不能更新为“完成目标”
  • “质量保证”或“所有者”组中的用户可以更新到四个目标中的任何一个

解决此问题的最佳方法是什么?

我已经有一个功能正常的功能视图,该视图可填充渲染表单,并使用适当的Model实例填充其字段。

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='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 = ScrumyGoal
        fields = ('goal_status',)

views.py

def move_goal(request, goal_id):
    is_admin = request.user.groups.filter(name=Group.objects.get(name='Admin')).exists()
    is_owner = request.user.groups.filter(name=Group.objects.get(name='Owner')).exists()
    is_developer = request.user.groups.filter(name=Group.objects.get(name='Developer')).exists()
    is_assurer = request.user.groups.filter(name=Group.objects.get(name='Quality Assurance')).exists()

    goal_instance = ScrumyGoal.objects.get(goal_id=goal_id)

    if request.method == 'POST':
        form = EditGoalForm(request.POST, instance=goal_instance)
        if form.is_valid():
            form.save()
            messages.success(request, 'Goal Update Successful')
            return redirect('home')                
        else:
            messages.error(request, 'Oops! Please try again!')
    else:
        form = EditGoalForm(instance=goal_instance)
    return render(request, 'move_goal.html', {'form': form})

我只需要有关如何做正确的事情的指针。您的帮助将不胜感激。谢谢!

0 个答案:

没有答案