Skip to main content

Posts

Showing posts with the label code

Django: adding additional Admin static and writing JS snippets for Django Admin

It often gets that you need it because you invent something that is meant to be displayed for admin. E.g. some nasty form field or something. Here is my recipe to add some additional Django static to your admin. Rather than writing a widget , that is more proper way here... I was using a widget already (from another package). So I could not use it properly, at least without a ton of overrides and complexity it leads to. SO I've decided to add the JS functionality to override a lack of backend. First of all we should add the javascript/css like so: # admin.py class MyModelAdmin (admin.ModelAdmin): # admin additions class Media : css = { "all" : ( "css/my_style.css" ,) } js = ( "js/my_script.js" ,) This add should list your files, loaded in the admin . So you can access them and see in the Django admin frontend itself. Like so: Now that your script and style are loaded you could jus...

Django: adding code execution on your app syncdb, or how to use Django Signals.

Hi there and let's talk about app initialization in Django. There are some cases when you want to initialize a Django app with creating some default values in database. In my case it was necessity to create default album in database to post user photos to. Sometimes you could just use get_or_create for those purposes. But it will be a good example if we will need something more complex in our app initialization; for e.g. generating thumbnails for photos or cleaning unused temporary files etc. So let's get started: Good place to put your initialization scripts is your app's __init__.py file. You can examine Djangoproject wiki for more info. Anyway here is my code for making this: from  django. db . models . signals   import  post_syncdb import  models from  models  import  Album   def  create_first_album ( sender,  ** kwargs ) :      """    Create your album sequence to create default album t...