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

change the default formating of the DateField in django forms Feb
23
1
1

Django forms are great, but sometimes you need to do a little work to get things just the way you want. The DateField has an easy way to restrict how data is entered through the input_formats option; but unless if I'm missing something there's isn't a similar way to help you set how the field displays the date in the template.

The default way the forms.DateField is displayed is YYYY-MM-DD, which is typically not what you want to present to the users.

The easiest way I have found to change how the date field displays is to write a small custom form field that inherits from forms.DateField that overrides the widget.

It would look something like this:

from django import forms
from django.utils.translation import ugettext_lazy as _


class FormattedDateField(forms.DateField):
    widget = forms.DateInput(format='%m/%d/%Y')

    def __init__(self, *args, **kwargs):
        super(FormattedDateField, self).__init__(*args, **kwargs)
        self.input_formats = ('%m/%d/%Y',)


class ProfileForm(forms.Form):
    email = forms.EmailField()
    first_name = forms.CharField(max_length=100)
    last_name = forms.CharField(max_length=100)
    birthday = FormattedDateField()

Or for a short-hand version that doesn't require overriding the form class could look something like the following:

class ProfileForm(forms.Form):
    email = forms.EmailField()
    first_name = forms.CharField(max_length=100)
    last_name = forms.CharField(max_length=100)
    birthday = forms.DateField(widget=forms.DateInput(format='%m/%d/%Y')), input_formats=('%m/%d/%Y',))

Now, when I initialize the birthday field in the form instead of displaying YYYY-MM-DD, it will look like MM/DD/YYYY which is more natural to an American audience.

comments

extracting key value pairs of an array in javascript with jquery Jan
06
1
1

At times I feel spoiled using Python, especially when I try to do what seems to be a trivial operation to discover there's not already a construct to do it in whatever language I'm in at the time. One of these instances is when I try to loop over and extract key value pairs out of an array in Javascript. Being in the Python mode I'm usually hoping to find something like the following:

# python
for key, value in array:
    ....

The best I could come up with is to use the each() function from JQuery to loop over each element.

var example = {};

example['apple'] = 1;
example['orange'] = 2;

$.each(example, function(key, value) {
    console.log(key);
    console.log(value);
});

Or, for a non-jquery solution:

for(var key in example) {
    console.log(key);
    console.log(example[key]);
}

comments

how to stop / terminate / exit a python script Jan
03
1
1

I know this could be trivial to some of you, but it wasn't obvious to me which is why I'm posting. From time to time you might want to hard exit out of your python script. For me this came about when I was writing some system deploy and maintenance scripts. Just returning out of a function wasn't good enough because the rest of the script would keep on trucking. I needed to stop all execution of the script right there before it continued on and did irreversible damage to the system.

This can be done through the sys module.

import sys
sys.exit()

It's good to note that all this does is throws a SystemExit exception which can be caught like any other exception.

Alternatively you can use the os._exit() function which terminates at the C level and does not let the interpreter perform any of the normal tear-down procedures. It is not recommended to use os._exit() as sys.exit() should suffice for the vast majority of cases and is the recommended method.

comments