manually writing to model filefield in django views Oct
11
1
1

Django models.FileField is very helpful in simplifying file management, but sometimes you need to write/overwrite into a file field object in a view without having the admin helper functions available. It's not inherently clear how to do this manually. Never fear though it's still an easy process.

It's worth noting that Django uses a custom File class that acts as a wrapper around the python file object to add some enhanced functionality. You simply need to initialize a Django File with a python file to get a valid model.

Say you have something similar to the following model:

class FileExample(models.Model):
    test = models.FileField(upload_to='uploads')

You can then write something like this in your view:

from django.core.files import File
from test.models import FileExample

file_example = FileExample()

filename = '/path/to/file.txt'
f = open(filename, 'r')
djangofile = File(f)
file_example.test.save('filename.txt', djangofile)
f.close()

Furthermore you can combine some statements to simplify and shorten the process:

file_example = FileExample()
file_example.test.save('filename.txt', File(open('/path/to/file.txt', 'r')))

comments

export a table into a csv file in postgresql Oct
05
1
1

I always have to look this up, so I'm placing this here. This exports a table into a csv file in PostgreSQL.

COPY (SELECT * FROM table) TO `/path/to/file.csv` WITH CSV HEADER;

comments

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

delete a remote branch in git Jul
21
1
1

It's not always clear how to delete a remote branch in git, but it's just the following command:

git push REMOTENAME :BRANCHNAME

 The syntax is a little wonky if you're not used to the advanced push syntax. If you look at the details of what's happening you're telling git to push nothing into the remote branch.

git push REMOTENAME LOCALBRANCHNAME:REMOTEBRANCHNAME

comments

flush dns cache on mac osx 10.5+ Jul
13
1
1

I'm not usually on a Mac, but several people I work with are and periodically they need to flush their local cache. I'm just throwing this here because I keep having to look this up. Just open the Terminal up and type the following:

dscacheutil -flushcache

comments

globally config git color Apr
06
1
1

git config --global color.ui true

comments

getting gmail to recognize the reply-to header Mar
30
1
1

I've been having issues with gmail not recognizing the reply-to email header when the "Reply-To" address was different than the "From" address. I inspected the headers and everything was set properly: something like:

from     "contact@example.com"
reply-to "user@gmail.com"
to       "contact@example.com"

In my case I am sending email to the site admin through a contact email form on the site. Because of the SMTP authentication security settings I'm forced to send the email from an authorized address. However, I want to reply to the user's email that they enter in the form. Because of this I can't set the "From" address to the address the user entered.

I noticed that gmail was ignoring the reply-to setting. When I replied to the email it was getting sent back to contact@example.com instead of user@gmail.com. Strangely, it turns out having the clients reply back to themselves wasn't exactly useful.

While doing some tests it seems that gmail ignores the "Reply-To" header when the "From" is one of the accepted "Send-As" addresses set in gmail. (Thank you Joshua) I don't know why this happens. Maybe it's a bug, maybe it's a security thing gmail is enforcing . . . I really don't have an answer why this happens.

After understanding what was happening to get around this behavior I set up a dummy email address, authorized it with the SMTP server, and forwarded all emails that get sent to the dummy address to the actual address that I want. The fields changed to something like:

from     "noreply@example.com"
reply-to "user@gmail.com"
to       "noreply@example.com"

and then I forwarded all emails sent to noreply@example.com to contact@example.com . After having that set up replies to the email correctly get sent to user@gmail.com instead of back to contact@example.com.

I know that it's not the most elegant setup, but hey, at least it works and the client is happy.

comments