Django表单 - 根据请求参数显示字段

时间:2017-03-09 16:37:01

标签: django django-forms django-views

我'以下django模型:

class OrderLog(models.Model):
    order = models.ForeignKey(Order)
    entry = models.TextField()
    private = models.BooleanField(default=False)

及相关表格:

class OrderLogForm(forms.ModelForm):
    class Meta:
        model = OrderLog
        fields = ('entry', 'order', 'private')

。如何根据请求参数修改fields参数?因此,如果用户是testuser,则字段元组仅包含前2个元素,在其他情况下包含3个元素。可以从表单本身以某种方式请求访问吗?

感谢。

2 个答案:

答案 0 :(得分:0)

在init中覆盖它,如下所示:

class OrderLogForm(forms.Form):
    def __init__(self, *args, **kwargs):
        # expects a request object to be passed in initially
        self.r  = kwargs.pop('request')
        super(FrageForm, self).__init__(*args, **kwargs)

    if 'value' in  self.r:
         self.fields["field1"] =  forms.CharField(initial=None)  
    else:
         self.fields["field1"] =  forms.CharField(initial=None)
         self.fields["field1"] =  forms.CharField(initial=None)

答案 1 :(得分:0)

最好只传递您需要的对象(在本例中为request.user),而不是传递整个request对象。

这是一个可能的解决方案:

class OrderLogForm(forms.ModelForm):
    class Meta:
        model = OrderLog
        fields = ('entry', 'order', 'private')

    user = None

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super(OrderLogForm, self).__init__(*args, **kwargs)
        if self.user.username == 'testuser':
            del self.fields['private']