On May 6, 10:47 am, NicoEchániz <lwcy...@gmail.com> wrote:
> On May 6, 8:57 am, Daniel Roseman <roseman.dan...@googlemail.com>
> wrote:
> > On May 6, 5:26 am, NicoEchániz <lwcy...@gmail.com> wrote:
> > > Hello,
>
> > > I have a model which has a ForeignKey to itself. I'm doing this to
> > > represent a hierarchy which I then need to display in the
> > > corresponding select field of my form.
> >[....]
> > > You can find the corresponding code snippet 
> > > here:http://dpaste.com/hold/41342/
>
> > Your code in lines 22 onwards is being executed when the form class is
> > defined. So the choices for robro_superior are being set at that
> > point, and not updated.
>
> > To fix this, put this code into an __init__() method. This is called
> > when the form is *instantiated* - so each time, it will get the list
> > fresh from the database.
>
> > class RubroForm(ModelForm):
> >     rubro_superior = ModelChoiceField(queryset=Rubro.objects.all(),
> > required=False)
>
> >     def __init__(self, *args, **kwargs)
> >         super(RubroForm, self).__init__(*args, **kwargs)
> >         r = Rubro.objects.all()
> >         choices = [('', '- - - -')] + [(rubro.id, rubro.jerarquia) for
> > rubro in r]
> >         choices.sort(key=itemgetter(1))
> >         rubro_superior.choices = choices
>
> > --
> > DR.
>
> Daniel,
>
> Thanks for your reply.
> I had already tried this, but there's another problem whith this
> solution. The class attribute rubro_superior seems inaccesible for
> some reason.
>
> I get the error:
> global name 'rubro_superior' is not defined
>
> I've tried changing the offending line:
> rubro_superior.choices = choices
>
> for:
> RubroForm.rubro_superior.choices = choices
> and for:
> self.__class__.rubro_superior.choices = choices
>
> to no avail...
>
> so... the description of the problem seems correct to me, but I can't
> find the way to solve it.
>
> Thanks,
>
> NicoEchániz


solved it after reading:
http://stackoverflow.com/questions/738301/how-to-modify-choices-of-modelmultiplechoicefield

I just needed to access the attribute like this:

self.fields['rubro_superior'].choices = choices

that did it.


Thanks for the help.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to