在某些情况下,我试图编写一个视图来编辑ModelForm的实例。我需要帮助来整理条件。用户可以属于四个组:Admin
,Developer
,Owner
和Quality Assurance
。数据库中有四个GoalStatus模型实例:每周目标,每日目标,验证目标,完成目标。现在的条件:
解决此问题的最佳方法是什么?
我已经有一个功能正常的功能视图,该视图可填充渲染表单,并使用适当的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})
我只需要有关如何做正确的事情的指针。您的帮助将不胜感激。谢谢!