0

I have faced this issue while creating a form using Django.

class DetailForm(forms.Form):
    row_id = 2

    def __init__(self, *args, **kwargs):
        global row_id
        row_id = kwargs.pop('r_id')
        super(DetailForm, self).__init__(*args, **kwargs)

    row=Prewash.objects.get(id=row_id)
    id = forms.CharField(label='ID',initial=row_id, widget=forms.TextInput(attrs={'readonly':'readonly'}))

Here within the init() the global variable row_id is being updated. But it does not get reflected in the last line when I try to retrieve the value from the db.

I need a way to retain the value of the variable I am trying to set within the constructor(without using instance or methods).

Sumit Roy
  • 49
  • 6
  • 2
    what are you exactly trying to do here? why not just assign value `self.row_id` instead of declaring global variables? – v1k45 May 02 '17 at 10:55
  • I have edited the question to serve your answer. I cant create the self instance because outside the constructor or function I can't use the self instance. Here I am trying to create a dynamic form. – Sumit Roy May 02 '17 at 11:01

2 Answers2

0

In a python class we use object attributes or static attributes. if you want access object attributes you have to use

self.<attribtute_name>

and if you want access static attributes we use

<<ClassName>>.<<attribute_name>>

See this link Static class variables in Python

Community
  • 1
  • 1
Adouani Riadh
  • 1,162
  • 2
  • 14
  • 37
  • Well I changed the code accordingly. def __init__(self, *args, **kwargs): DetailForm.row_id = kwargs.pop('r_id') row=Prewash.objects.get(id=DetailForm.row_id) But now I get an error: row=Prewash.objects.get(id=DetailForm.row_id) NameError: name 'DetailForm' is not defined – Sumit Roy May 02 '17 at 11:07
0

If you want to change field attributes based on then form's context, you can do that by accessing and updating that specific field in the __init__ function.

Something like this should work:

class DetailForm(forms.Form):
    id = forms.CharField(label='ID', widget=forms.TextInput(attrs={'readonly':'readonly'}))

    def __init__(self, *args, **kwargs):
        row_id = kwargs.pop('r_id', 2)
        super(DetailForm, self).__init__(*args, **kwargs)

        self.fields['id'].initial = row_id
v1k45
  • 8,070
  • 2
  • 30
  • 38