Showing posts with label when. Show all posts
Showing posts with label when. Show all posts
Thursday, June 29, 2017
Django Reminder Delete File when deleting object
Django Reminder Delete File when deleting object
For Django FileField objects and object of its subclasses, when using the objects delete() method, it will only delete the object record from the database, the file will remain in the appointed location in your servers filesystem.
After a few research, it is a deliberate design in Django to prevent unwanted mess in database when rolling back an record (not sure how this is doable though, leave comments if you know how :D).
So, we have to explicitly delete the file from the filesystem ourselves using
FileFieldObject.file_field.storage.delete(filepath)
A simple implementation to delete the file when delete the file object from db would be like this:
f = FileFieldObject #replace with your models .objects.get() here
storage = f.file_field.storage
#field_field is the property in your model which is an object of class model.FileField
path = f.field_field.path
storage.delete(path) #delete file from disk
f.delete() #delete record from db
Monday, June 12, 2017
Detect when a user stops typing with jQuery
Detect when a user stops typing with jQuery
When writing forms I frequently find I need to do some of my validation server side(for example checking if a username is already taken) but want to have a responsive real-time field validation displayed to the user. Obviously this effect can be achieved using AJAX but if you want to validate while the user is typing sending an AJAX request on every keypress is a very inefficient way of doing things. It seems to me that a "onInputFinished" event is needed so that you can detect and take action when a user stops typing in an input field.
I had a bit of a google around and couldnt find an elegant solution for it so I decided to roll my own using jQuery. This simple jQuery script allow you to add the "onfinishinput" attribute to HTML input fields in the same way you would use normal onclick and onkeyup events.
you can check out a working example here:
http://dl.dropbox.com/u/6217043/js-example/example.html
Using the Script:
After including the script on your page you can use the new event like this:
<input type="text" onfinishinput="alert(You typed + input_field.val())" />
NOTE: instead of using "this" when referring to the element use "input_field" like the example above.
Installing the Script:
The script can be downloaded from here:
http://dl.dropbox.com/u/6217043/js-example/onfinishinput.js
The script requires jQuery to function, the latest jQuery can be downloaded from here:
http://jquery.com/
Just include the scripts on your page and you are ready to go.
Subscribe to:
Posts (Atom)