September 2011

archive

uploading multiple files with the same input name in django Sep
20
1
1

So sometimes I have an input field in a form that I want to upload files to but I want to upload multiple files at a time. I'll usually just use javascript to add and remove the field dynamically, and to keep things simple I'll keep the input name the same. I'll eventually end up with markup that looks similar to the following:

<input type="file" name="file" />
<input type="file" name="file" />
<input type="file" name="file" />

Django attaches the uploads in the FILE dictionary variable on the request object which you can access like so:

for uploaded_file in request.FILES['file']:
    # process the file

which could look something like:

# views.py
from django.http import HttpResponseRedirect

def upload_file(request):
    for uploaded_file in request.FILES.getlist('file'):
        handle_uploaded_file(uploaded_file)

    return HttpResponseRedirect(...)


def handle_uploaded_file(f):
    destination = open('/upload/path/%s' % f.name, 'wb+')

    for chunk in f.chunks():
destination.write(chunk) destination.close()

comments

extract or return only the model instance of a foreign key or one to one field from a queryset in django Sep
14
1
1

Lets say I have two models connected by a OneToOne field like so:

class Post(models.Model):
    ...


class MagicalPost(models.Model):
    post = models.OneToOneField('Post')
    pony = models.TextField(max_length=100, help_text='This is where the MAGIC happens!')

I want to run a query over all MagicalPost objects but I only want to receive the Post instances.

I can use the select_related() option which will only create one database call:

magical_posts = MagicalPost.objects.select_related('post')
posts = []

for magical_post in magical_posts:
    posts.append(magical_post.post)

return posts

Or I could use two queries which syntactically is simpler:

posts_ids = MagicalPost.objects.values_list('post', flat=True)
posts = Post.objects.filter(id__in=posts_ids)
return posts

comments

create the directories if they don't exist in Python Sep
01
1
1

import os


directory = 'path/to/folder'

if not os.path.exists(directory):
    os.makedirs(directory)

comments

how to execute a string in python Sep
01
1
1

To run a string use `exec`

code = 'print "Hello World"'
exec code

If you need to pull a value from an expression use `eval`

foo = eval('1+1')

comments