python - Django access data passed to form -


I got a choiceField in my code, where I show filtered data. I need two arguments to filter the data. I do not have a problem at first, because I can take it directly from an object, but the second one is dynamically generated, here is some code:

  class groupAd (forms.Form): def __init __ (self, * args, ** kwargs): self.pid = kwargs.pop ('parent_id', none) Super group (add, self) .__ init __ (* args, ** kwargs) parent_id = forms.IntegerField (widget = forms.HiddenInput) option = forms.ChoiceField (option = [[group.node_id, group.name] for group Filter in Objtree (name = 'group'), parent_id = 50) .distinct ()] + [[0, 'add a new one]]], .bjects.exe; Widget = forms.Select (attrs = {'id': 'group_select'}))  

I would like to change the parent_id passed in Objtree.objects.filter . As you can see, I tried to call init function, as well as call with kwargs ['initial'] ['parent_id'] and then with self , But that does not work, because it is out of the scope ... this was my last attempt, enough to enter it either in the initial parameter or straight trough parent_id field Is required because it already holds its value (passed trough initial ).

Any help is appreciated, as I am out of ideas. Before I answer your question about some minor points

First of all, your field should probably be a ModelChoiceField - instead of a list of options , It takes a queryset parameter, which avoids the requirement for it and understanding the list to get the value.

Secondly, to get Objtree objects, your query is better by using double-underscore notation to exceed better relations:

  Objtree Objects.filter ( Type__name = 'group', parent_id = 50)  

Now, the real question. As you note, you can not reach local or example variables within field declarations. These are class-level characteristics, which are processed (through metaclass) when class is defined, not when it is instant, you need to do all the things in __init __ .

Like this:

  class GroupAdd (forms.Form): parent_id = forms. IntegerField (widget = forms.HiddenInput) option = forms.ModelChoiceField (queryset = none) def __init __ (auto, * args, ** kwargs): pid = kwargs.pop ('parent_id', none) Super (GroupAdd, Self). __int __ (* Args, ** kwargs) self.fields ['Options']. Queryset = Objtree.objects.filter (type__name = 'group', parent_id = pid)  

Comments

Popular posts from this blog

windows - Heroku throws SQLITE3 Read only exception -

lex - Building a lexical Analyzer in Java -

python - rename keys in a dictionary -