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. > > I've come up with a simple custom Form which represents my select > choices like this: > --------- > level0.a > level0.a > level1.a > level0.a > level1.b > level0.b > > etc. > > You can find the corresponding code snippet here:http://dpaste.com/hold/41342/ > > It's all working well but I seem to have some sort of cache or class > lifespan problem... the thing is that whenever I add a new item it > does not get displayed in the select choices next time I visit the > form. I need to reload the page a bunch of times for it to show up. > > So, what do I need to do to avoid this behaviour? > > Thank you all very much in advance, > NicoEchániz
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. --~--~---------~--~----~------------~-------~--~----~ 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 -~----------~----~----~----~------~----~------~--~---