Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django query executed in view returns old data

I have a view which queries a model to populate a form:

class AddServerForm(forms.Form):
    …snip…
    # Compile and present choices for HARDWARE CONFIG
    hwChoices = HardwareConfig.objects.\
        values_list('name','description').order_by('name')
    hwChoices = [('', '----- SELECT ONE -----')] +\
        [ (x,'{0} - {1}'.format(x,y)) for x,y in hwChoices ]

    hwconfig = forms.ChoiceField(label='Hardware Config', choices=hwChoices)
    …snip…

def addServers(request, template="manager/add_servers.html",
    template_success="manager/add_servers_success.html"):
    if request.method == 'POST':
        # …snip… - process the form
    else:
        # Page was called via GET - use a default form
        addForm = AddServerForm()

    return render_to_response(template, dict(addForm=addForm),
        context_instance=RequestContext(request))

Additions to the HardwareConfig model are done using the admin interface. Changes show up immediately in the admin interface as expected.

Running the query via the shell returns all results as expected:

michael@victory> python manage.py shell
Python 2.6 (r26:66714, Feb 21 2009, 02:16:04)
[GCC 4.3.2 [gcc-4_3-branch revision 141291]] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from serverbuild.base.models import HardwareConfig
>>> hwChoices = HardwareConfig.objects.\
...         values_list('name','description').order_by('name')

hwChoices now contains the complete set of results.

However, loading the addServers view (above) returns the old result set, missing the newly-added entries.

I have to restart the webserver in order for the changes to show up which makes it seem as though that query is being cached somewhere.

  • I'm not doing any explicit caching anywhere (grep -ri cache /project/root returns nothing)
  • It's not the browser caching the page - inspected via chrome tools, also tried using a different user & computer

What's going wrong and how do I fix it?


Versions:

  • MySQLdb: 1.2.2
  • django: 1.2.5
  • python: 2.6
like image 282
MikeyB Avatar asked Nov 22 '25 07:11

MikeyB


1 Answers

hwChoices is evaluated when the form is defined - ie when the process starts.

Do the calculation in the form's __init__ method instead.

like image 102
Daniel Roseman Avatar answered Nov 23 '25 22:11

Daniel Roseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!