views:

28

answers:

2

I have a Django app, which populates content from a text file, and populates them using the initial option in a standard form. The file gets updated on the server, but when the form gets refreshed, it picks up content from the a previously saved version, or the version before the Apache WebServer was reloaded.

This means that the file is getting cached, and the content is picked up from a wrong cache and not the new file.

Here is my code. How do I ensure that everytime, spamsource function picks up the content from the most recently saved file, instead of from a cache.

def spamsource():
   try:
    f= open('center_access', 'r')
    read=f.read()
    # some manipulation on read 
    f.close()
    return read
   except IOError:
    return "prono.nr"

class SpamForm(forms.Form):

    domains =forms.CharField(widget=forms.Textarea(attrs=attrs_dict),
                                label=_(u'Domains to be Banned'), initial= spamsource())
def function(request):
    # It writes the file center_access based on the changes in the textbox domains
+3  A: 

The issue is simply that all the parameters to fields are evaluated at form definition time. So, the initial value for domains is set to whatever the return value is from spamsource() at the time the form is defined, ie usually when the server is started.

One way of fixing this would be to override the form's __init__ method and set the initial value for domains there:

class SpamForm(forms.Form):
    domains = ...

    def __init__(self, *args, **kwargs):
        super(SpamForm, self).__init__(*args, **kwargs)
        self.fields['domains'].initial = spamsource()

Alternatively, you could set the initial value when you instantiate the form in your view:

form = SpamForm(initial={'domains': spamsource()})
Daniel Roseman
No. This Does not work. I still need to restart the Apache web server to get the results. There has to be someway to remove the file cache and load it again
ramdaz
Which one doesn't work? There's no such thing as caching of file operations in Django, so there's something going on that you're not telling us.
Daniel Roseman
+1 Function definition getting a value from the method is an undebugable error. Everybody gets bitten once!
Lakshman Prasad
A: 

I fixed this. The problem was the presence of all the caching middleware in settings.py, which were being used to speed up another side of the web app.

ramdaz