Posts Tagged ‘django’

Working with files in Django – Part 3

Wednesday, November 30th, 2011

First part of this article is here.

How to add STATIC files

You will most likely add STATIC files to your source code repository. As they are likely to be hardcoded in your code and templates it is a good idea to keep those and your STATIC files in sync.

Your STATIC files are collected (found and copied or symlinked) with the help of finders. This collection process might be a little confusing for you. Basically you don’t need to worry about where your files are copied, you just need to maintain the files in the locations I mention below. Collection process consolidates all your STATIC files for you, and it does it automatically.

If you are developing a reusable app place your STATIC files under the static directory. Your app directory should look like this:

$ ls -1
models.py
static/
templates/
views.py

If you are developing a project absolute filesystem paths listed in your STATICFILES_DIRS setting will be collected:

>>> from django.conf import settings
>>> settings.STATICFILES_DIRS
('/opt/myproject/src/project/static',)

One important thing to note, as I mentioned in the first part, is to set your STATIC_ROOT outside of your project directory. This is the location where all the STATIC files found will be consolidated. Making this directory independent from your project installation enabled its reuse.

How to upload MEDIA files

MEDIA files are typically uploaded by users when the project is online and a reference is stored in a model field. While this is true most of the time, MEDIA files can be generated by code and/or a reference can be provided in some other way that doesn’t involve models. But these edge cases are out of the scope of this post.

The easiest way to allow users upload their files is to use a FileField or ImageField on a model and derive a form from it:

from django.db import models
from django.forms.models import modelform_factory


class MediaModel(models.Model):
    media_file = models.FileField(upload_to='user_media')


MediaForm = modelform_factory(MediaModel)

You can then use this form to provide upload functionality:

def media_create(request):
    if request.method == "POST":
        form = MediaForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('media-list'))
    else:
        form = MediaForm()
    return render_to_response('usermedia/create/html', {'form': form})

Of course it is better to use a generic CreateView now we have them with Django 1.3. I wanted to emphasize one point and avoid the complexities of a class based view; you must pass request.FILES to the form’s constructor. Actually this is a good practice whether or not your form has an file field.

As in the case with STATIC files, MEDIA_ROOT should be in a location seperate from your project files. If you delete your project directory you would also lose MEDIA files otherwise.

Conclusion

This concludes Working with files in Django. I hope these posts are helpful to you. Once you are comfortable working with files I strongly recommend you to take a look at Django Compressor

If you enjoyed this post please tell me a little bit about yourself.

Bookmark and Share

Working with files in Django – Part 2

Saturday, November 26th, 2011

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 getstaticprefix 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.

If you enjoyed this post please tell me a little bit about yourself.

Bookmark and Share

Working with files in Django – Part 1

Monday, November 21st, 2011

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.

How to configure STATIC/MEDIA related settings

Let’s look at some code first and we can comment on it afterwards. I use the following setup in my projects:

import os

_PATH = os.path.abspath(os.path.dirname(__file__))

MEDIA_ROOT = os.path.join(_PATH, 'files', 'media')
MEDIA_URL = '/media/'

STATIC_ROOT = os.path.join(_PATH, 'files', 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(_PATH, 'static'),
)
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

ADMIN_MEDIA_PREFIX = '/static/admin/'

_PATH should be obvious. But the way I use it is a little tricky here. Basically I am using a files directory that contains media, for MEDIA files, and static, for STATIC files, directories. This seperation is essential. You will pull your hair if you don’t seperate those two from the beginning. This will allow you to reuse them easily if you deploy a new version to a different location.

But why is files under the project directory? Because we need to check-in STATIC files? NO! It is just a convenience for the development environments. I strongly suggest overriding MEDIA_ROOT and STATIC_ROOT in your deployment settings and basically move the files directory outside of the project path. STATIC files that we check-in resides in <_PATH>/static. django.contrib.staticfiles app collects your STATIC files from your project specific directories and within your apps and copies everything in the right places inside STATIC_ROOT.

To sum up the points above:

  • Check-in STATIC files in a folder within your project directory (see STATICFILES_DIRS & FileSystemFinder). If you are developing an app AppDirectoriesFinder will collect static files within the static directory in your app directory.
  • Seperate the directories, where your MEDIA files are saved and where your STATIC files are collected (see STATIC_ROOT & MEDIA_ROOT).
  • Keep your STATIC_ROOT and MEDIA_ROOT outside of your project directory in production environment.

One more thing to note is STATIC_URL and MEDIA_URL should both have a trailing slash. This will save you a lot of trouble later.

Next part deals with serving files in development environment and referencing them in code and templates.

If you enjoyed this post please tell me a little bit about yourself.

Bookmark and Share

My PyCon APAC 2011 Presentation: Optimizing Media Performance with django_compressor

Tuesday, June 28th, 2011

I have given a presentation about django_compressor at PyCon APAC 2011. Slides are below for everyone to see:

Bookmark and Share

I Am Discontinuing Telvee

Thursday, September 2nd, 2010

Telvee was originally a Facebook app. It was Burak Büyükdemir‘s idea to create a virtual coffee reading app. Rakı Sofrası was super popular then. We have quickly built and deployed and getting some good results. But the competition wasn’t fair.

When I decided to give this software a fair chance to succeed on its very own domain the only question in my head was; will it pass the test of users? It doesn’t really matter what you have intended the users do with your application. What matters, first, is what they think they’d like to do with it and then whether or not they actually use it.

So I tried and I failed. Two main reasons of this failure are; technical deficiencies and the special way of interaction coffee reading is. Technical deficiencies is the easy one. I couldn’t devote enough time for telvee, especially lately. As a result it doesn’t even have basic stuff like e-mail changing or account deletion. This is 100% my fault. The second reason however is more complicated and there was not much I could do about it. Except one thing I will tell you at the end of this post.

Telvee didn’t pass the user’s test mainly because coffee reading is somewhat private. It’s more of a 1-to-1 communication, while all social applications1 are designed for 1-to-many communication. This was disastrous not only because of the lack of viral growth but also because of the reluctance of users to interact with other users.

An example image of coffee remains telvee generates

An example image of coffee remains telvee generates

I would like to thank everybody who participated and I hope you had some fun playing with it. Telvee domain will soon redirect to this post and I will probably not renew it next time.

I won’t be starting a new experiment soon. I will spend most of my time on my work. Hopefully I will be spending a little more time on free software projects. By the way I would like to note that Telvee has spawned a couple of Django apps: django-inviting & django-simple-friends.

Oh, and the thing I could do better about user experience was to be more agile. I should have either fixed the problem quickly or failed fast. I have no regrets though. This was a unique experience and I have learned a lot.


1: Yes, even the e-mail system and dating sites are designed for 1-to-many communication primarily in mind.

Bookmark and Share