Oct 31, 2011

Django: compressing CSS/JS files with django-compressor

There are 2 main usual tasks with web project's deployment and about .css and .js files.
First one - size minimization. But there are lot's of utilities helping you to compress CSS files. Delete unused spaces, comments and so on... Second one - Version control. For e. g. When you've updated the script on your deployment server, but user's browser uses old one until user manually hits 'Refresh'.
That's where Static files compressor comes in to mind.

Upon selecting among available one's found top "google" results:
- django-compress
- django-compressor
- webassets

Project uses 'django.contrib.staticfiles', so django-compress was not compatible... It does not support Django's static files gently. Webassets s a good lib. but project has a huge amount of different static. Maybe it's ok for e small project, but when you need to specify/change a 100's javascript in python module for certain templates... Nothing good comes in mind. And imho TEMPLATES... That's where thing's like those should live.

So Django-compressor was chosen using those criteria. And, to mention, project is actively developed, supported and documented. Anyway adding it to your django project is quite simple, as most good apps.

What it does, it turns this:

<script type="text/javascript" src="{{ MEDIA_URL }}public/js/jquery-1.4.1.min.js"></script>
<script type="text/javascript" src="{{ MEDIA_URL }}banners/js/jquery.cycle.all.js"></script>
<script type="text/javascript" src="{{ MEDIA_URL }}js/gb/greybox.js"></script>
<script type="text/javascript">
jQuery.browser.msie6 = jQuery.browser.msie && parseInt(jQuery.browser.version) == 6 && !window["XMLHttpRequest"];

if (!jQuery.browser.msie6) {
   $("div#body_wrapper").wrap('<div id="body_wrapper_shadow_right"><div id="body_wrapper_shadow_left">'+

Into this:

<script type="text/javascript" src="/static/CACHE/js/8dd1a2872443.js" charset="utf-8"></script>

The install is quite simple and you need to follow this manual.
Then configure it. Basically you hava all set for it to function. Except for me having a bit wired way of storing static files. I had to remap default COMPRESS_ROOT and COMPRESS_URL variables. It's quite easily done in settings.py. And it has lot's of other settings, that I did not require.

Anyhow this is it. Now you can wrap all of your code with handy templatetags that will do all the work for you. it may look somehow like this:

{% load compress %}

{% compress css %}
<link rel="stylesheet" href="/static/css/one.css" type="text/css" charset="utf-8">
<style type="text/css">p { border:5px solid green;}</style>
<link rel="stylesheet" href="/static/css/two.css" type="text/css" charset="utf-8">
{% endcompress %}

or for .js files:

{% load compress %}

{% compress js %}
<script src="/static/js/one.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">obj.value = "value";</script>
{% endcompress %}

It will generate a custom .js/.css files with all of your compressed static at one file in your media/static dir that can be cashed. They will have links, like "/media/CACHE/css/105dsb963311.css"and put your newly generated script/style there. 

This is it. Use this in your projects. It economies your server's time/traffic and helps you to update scripts at all user's clients in their browsers when you deploy a new version.

Liked/used/hated/disliked/have a better way? Please leave a comment here about what and/or how you did this/suggest me to do this?

Oct 26, 2011

Django: 'ManyRelatedManager' object is not iterable

Upon development proces you often meet ManyToMany relations that throw errors in templates. I prefer to feed everything to context and play with it there.

This kind of error appears when you iterate through a model's ManyToMany field. To fix it just add a related 'all' manager through dot syntax. Like so:


class BannerImage(models.Model):
    image = models.ImageField(upload_to="somedir")

    def get_image_url(self):
        return 'Image url here'

class Banner(models.Model):
    name = models.CharField(max_length=250, null=True)
    images = models.ManyToManyField(BannerImage)

View/Tag or else, that creates context:

banner = get_object_or_404(Banner, pk=1)
return {'banner': banner,}

Template causing the error:

{% for image in banner.images %}
    <img src="{{ image.get_image_url }}" />
{% endfor %}

Template without the error:

{% for image in banner.images.all %}
    <img src="{{ image.get_image_url }}" />
{% endfor %}

I wrote this article for myself for remembering. I always forget this little thing. But if this method works for your case fill free to drop a "thankyou" comment or +1.