Working with files in Django - Part 2
First part of this article is here.
How to setup file serving for development server
As I mentioned earlier, it is best to serve files on a fast HTTP server. But this setup is overkill for development environments, you can safely let Django handle your files. The snippet below relies on the assumption, behind the scenes, that DEBUG is always True in development environment and it is always False in production environment. It should be fine for the purposes of this post:
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
It is quite straightforward. Nothing gets added to urlpatterns unless DEBUG is True and prefix (MEDIA_URL and STATIC_URL) is not a fully qualified URL.
How to reference STATIC files in templates
There are two ways to reference any file. You can use a file’s location in your file storage (your filesystem for example) for internal use. Or you can build a URL for the file so that clients can access it. This post will cover the latter, as the former is a simple matter of applying os.path.join() to STATIC_ROOT and the particular file’s path.
To build a URL in your templates you can simply concetenate STATIC_URL with the file’s relative location to it:
<img src="{{ STATIC_URL }}myapp/img/logo.png" />
However, to have STATIC_URL available within your template context you need to make sure of two things:
- The template needs to be rendered with a RequestContext.
- django.core.context_processors.static needs to be included in TEMPLATE_CONTEXT_PROCESSORS setting.
I can’t think of a reason why, but if for some reason you are not using RequestContext, you can provide STATIC_URL using get_static_prefix tag:
{% load static %}
{% get_static_prefix as STATIC_URL %}
<img src="{{ STATIC_URL }}myapp/img/logo.png" />
How to reference MEDIA files in templates
Dealing with MEDIA files is much simpler. The FieldFile object returned by ImageField and FileField has path and url properties and you don’t need to do concetenation yourself:
<img src="{{ some_model.some_image_field.url }}" />
Next part deals with adding files to your project.
Working with files in Django - Part 1
In this post what I mean by file is any content that is not dynamically generated. There are basically two types of files a web application deals with:
- Files that are hard coded in templates or in code. We will call them STATIC files.
- Files that are referenced in the code but only known in the run time. We will call them MEDIA files.
Now of course all these files are static and most of them can be classified as media, but I chose those terms because that more or less how they are referred to in Django documentation.
Since files are stored on disk or some other storage backend it is best to serve them on a fast HTTP server and let Django handle only dynamic content.
Was it the imperialism that made the west rich?
I had a friend who kept talking about how he cares about ideology and how he is willing to sacrifice and all… In the meantime he was in a bad financial state. It could prevent him continuing his education. He changed the topic back to politics and socialism when I asked what he was going to do about his own situation. I had to end the conversation by saying “save yourself first, then you can save the world” finally. I had enough with that.
I remembered that conversation when I was watching the TED talk The 6 killer apps of prosperity by Niall Ferguson. It is not an in depth analysis of course, but underlines some of the obvious facts and also includes some surprises.
This talk also touches how Ottoman Empire lost its power by giving in to bigotry. And the funniest thing is, according to the speaker, İbrahim Müteferrika was the one who realized the advantages of western empires. The very own İbrahim Müteferrika of Ottoman Empire, who brought the printing technology.
Oh, and it ends with a surprise. If you are really observant or you have watched it till the end, you will see that the trend is reversing.
Sign of a Stupid Programmer
if some_boolean_expression:
return True
else:
return False
Unlike programmers who can’t program, stupid programmers can and do program. That is the problem.
joined = '%s%s%s%s%s%s' % (
some_list[0],
some_list[1],
some_list[2],
some_list[3],
some_list[4],
some_list[5],
some_list[6])
You just wish they were unable to program. Every single time you encounter their code you question yourself. You ask if this is programming, what the f#ck is it I have been doing all this time?
def __unicode__(self):
return '%s' % self.some_unicode_attribute
I have been reading on stupidity lately. It all started with Onur tweeting this article. Then I have found the following definition of stupidity:
A stupid person is a person who causes losses to another person or to a group of persons while himself deriving no gain and even possibly incurring losses.
They’re both good reads. I just wish I was introduced to these concepts earlier. I felt stupid for my ignorance on stupidity.
def some_func(**kwargs):
param1 = kwargs.get('param1', 'param1_default')
param2 = kwargs.get('param2', 'param2_default')
param3 = kwargs.get('param3', 'param3_default')
param4 = kwargs.get('param4', 'param4_default')
param5 = kwargs.get('param5', 'param5_default')
param6 = kwargs.get('param6', 'param6_default')
Watch out for the stupid programmer. He is destructive.
Our Fear of Success, Reptilian Brain and Principles
I have been reading whatever I can find about game theory1 for some time. I am trying to understand the fundamental rules behind how we make our decisions. One thing that fascinated me all my life is human beings’ unwillingness to walk the path, that which has been demonstrated to yield better results with not significantly more requirements than the alternatives. One instance is very well described in this article. I will not go into the details and try to analyze it.
I have learned to recognize this behaviour and walk away. There are better ways to waste your time than trying to convince someone who doesn’t want to help himself, to do something fruitful. This education cost me a lot of time. But I think I have finally learned.
While I was reading Ray Dalio’s Principles, I found these two paragraphs below. They simply explain the whole issue:
Unlike any other species, man is capable of reflecting on himself and the things around him to learn and adapt in order to improve. He has this capability because, in the evolution of species man’s brain developed a part that no other species has—the prefrontal cortex. It is the part of the human brain that gives us the ability to reflect and conduct other cognitive thinking. Because of this, people who can objectively reflect on themselves and others —most importantly on their weaknesses are—can figure out how to get around these weaknesses, can evolve fastest and come closer to realizing their potentials than those who can’t.
However, typically defensive, emotional reactions—i.e., ego barriers—stand way of this progress. These reactions take place in the part of the brain called the amygdala. As a result of them, most people don’t like reflecting on their weaknesses even though recognizing them is an essential step toward preventing them from causing them problems. Most people especially dislike others exploring their weaknesses because it makes them feel attacked, which produces fight or flight reactions; however, having others help one find one’s weaknesses is essential because it’s very difficult to identify one’s own. Most people don’t like helping others explore their weaknesses, even though they are willing to talk about behind their backs, For these reasons most people don’t do a good job of understanding themselves and adapting in order to get what they want most out of life. In my opinion, that is the biggest single problem of mankind because it, more than anything else, impedes people’s abilities to address all other problems and it is probably the greatest source of pain for most people.
If we can successfully classify people into these two groups, I think we can do more meaningful things. Of course, it’s OK to become friends with the people who fall into the second category. As long as you don’t forget about their limitations and pick suitable activities.
Now, the second group of people are quite a different story. They would not only accept your help for their personal development, they would welcome it. But, why should we care? It’s their personal development, their problem. Shouldn’t we be worried about our own personal development? These people would have a momentum in their life that will affect your own pace. Moreover they will probably try to engage you and try to help you overcome your weaknesses. You should be worried about your own growth primarily. This is why surrounding yourself with these people is a great idea.
I have been very fortunate to meet people who are not afraid to review and renew themselves. I have managed to understand myself and others better, thanks to their mentoring. You don’t need to wait for a mentor to appear out of nowhere2 and give you all the answers and keys though. You can start with Seth Godin’s Quieting the Lizard Brain talk (below) and hopefully begin learning and changing things. After all noone can adapt for you, you will eventually need to exert some effort. Great effort.
1: Also I have been reading about game design but it is not really related to this post.
2: I consider myself really, really lucky, what kind of person would I be if those fantastic people hadn’t appear out of nowhere. I don’t think I would have ever dared to challenge myself.