0

i' ve the following django model:

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

and the related form:

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

. How can i modify the fields parameter based on the request parameter? So, if the user is testuser, than the fields tuple contains only the first 2 elements, in other cases 3 elements. Can request be accessible somehow from the form itself?

Thanks.

user2194805
  • 1,201
  • 1
  • 17
  • 35
  • U might want to check this http://stackoverflow.com/questions/1057252/how-do-i-access-the-request-object-or-any-other-variable-in-a-forms-clean-met – Abijith Mg Mar 09 '17 at 16:42

2 Answers2

0

Overwrite it in init like this:

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)
mtt2p
  • 1,818
  • 1
  • 15
  • 22
  • Passing the request parameter works fine, thanks, but setting the field does not really. If i try it within the init method, i got that the form does not have a fields attribute. If i try it outside of the init method, i got that self does not exists. – user2194805 Mar 09 '17 at 17:18
  • Ah, sorry, now it works, just can You please move the "if" section into the __init__ ? – user2194805 Mar 09 '17 at 17:22
0

Its better to pass only the object you need (in this case request.user) rather than passing the entire request object.

Here is a possible solution:

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']
flowfree
  • 16,356
  • 12
  • 52
  • 76