2010-09-08 61 views
0

值我有以下型号Django表单排除choicefield

class ActionConfirm(models.Model): 
    CONFIRM_METHOD = (
     (u'ce', u'Certificate'), 
     (u'tf', u'Trainee Feedback'), 
     (u'ms', u'Multi Source Feedback'), 
     (u'rp', u'Reflection upon Practice'), 
     (u'ot', u'Other - Please add/describe') 
    ) 

    confirm_method = models.CharField(max_length=2, choices=CONFIRM_METHOD) 
    user = User 

和下面的表格

class ActionConfirmForm(forms.ModelForm): 
    class Meta: 
     model = ActionConfirm 

,我知道我可以做

selected = ActionConfirm.objects.filter(user=user) 
得到他们目前的选择

那么如何从他们已经选择的confirm_method字段中排除值呢?

如果它是从一个数据库我知道我可以做choices = ActionConfirm.objects.exclude(choice__in = selected)但我不知道如何做它时,它是从元组元组。

+0

只是为了澄清 - 你试图使它所以用户只能创建'ActionConfirm'实例与'confirm_method'值*它们*没有用于以前创建的'ActionConfirm'实例? – 2010-09-08 08:39:25

+0

是的,这是正确的。我没有把上面的ActionConfirm模型中的所有字段。还有一个用户字段,并且selected =应该是ActionConfirm.objects.filter(user = user)而不是ConfirmChoices。现在应该更新 – John 2010-09-08 08:44:44

回答

2

您不显示ActionConfirmConfirmChoices之间的关系。为什么confirm_method是CharField而不是ForeignKey?

但是,如果你能得到选中的选项,你可以在形式的__init__其排除:

def __init__(self, *args, **kwargs): 
    super(ActionConfirmForm, self).__init__(*args, **kwargs) 
    selected_choices = whatever 
    self.fields['confirm_method'].choices = [(k, v) for k, v in CONFIRM_METHOD 
              if k not in selected_choices] 
+0

'confirm_method'是一个CharField,因为它是一个带有双字符“键”的元组('CONFIRM_METHOD'),而不是对单独模型的引用。 – 2010-09-08 08:52:42

+0

@Dominic是的,我对(Confirm-Remove)模型的(现在删除的)引用感到困惑。 – 2010-09-08 09:30:34