我正在使用模型表单,并且该字段是外键,对于另一个模型,外键模型包含我想要基于用户组过滤的选择字段(状态),这样如果用户属于一个组,例如,如果组中的用户是DEVELOPER,则可用的状态选项将是“每周任务”和“每日任务”
models.py
class ScrumyGoals(models.Model):
user_name=models.ForeignKey('ScrumyUser', on_delete= models.CASCADE, null= True)
status_id = models.ForeignKey('GoalStatus', on_delete=models.CASCADE,null=True)
goal_type = models.CharField(choices=GOAL_TYPE, max_length=64, default='DT')
def __str__(self):
return '{},{}'.format(self.user_name,self.status_id)
class GoalStatus(models.Model):
GOALS_TYPE= (('DT','Daily Task'),
('WT','Weekly Task'),
('V','Verified'),
('D','Done'),
)
title = models.CharField(max_length=254, null=True)
task_id=models.IntegerField(default=1,null=False)
description =models.CharField(max_length=254)
verified_by=models.ForeignKey('ScrumyUser', on_delete= models.CASCADE, null=True)
status=models.CharField(choices=GOALS_TYPE, max_length=2, default='DT')
forms.py
class ChangeTaskForm(forms.ModelForm):
class Meta:
model = ScrumyGoals
fields = ['status_id']
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(ChangeTaskForm, self).__init__(*args, **kwargs)
if user.groups.filter(name ='DEVELOPER').exists():
self.fields['status'].choices = (('WT','Weekly Task'), ('DT','Daily Task'),)
views.py
def changetask(request):
if request.method == 'POST':
form = ChangeTaskForm(request.POST, user=request.user)
if form.is_valid():
return HttpResponseRedirect('/index/')
else:
form = ChangeTaskForm(user=request.user)
return render(request, 'oderascrumy/changetask.html', {'form': form})
表单目前仅显示status_id,它不显示选项(即“状态”)
所以本质上我想要的是如果登录用户在群组中说“开发者”,用户只能将目标(即“status_id”)选择(即“状态”)从每周任务改为日常任务并保存表格
答案 0 :(得分:0)
如果您从forms.py中移除if
,它是否有效,即您是否对名称为' DEVELOPER'存在,并且您正在测试的用户实际上是在该组中吗?
另一种方法可能是始终在status
中加入fields
,然后只是通过if user.groups in ['DEVELOPER']
有条件地在模板中显示该字段。