get the current site object in a django view Mar
22
1
0

You can use the default Sites framework to get the current site in a django view.

from django.contrib.sites.models import Site

site = Site.objects.get_current()
domain = Site.objects.get_current().domain

or

from django.contrib.sites.models import Site
from django.conf import settings

site = Site.objects.get(id=settings.SITE_ID)

comments

have your django project use an external SMTP server Mar
22
1
0

Most of the time I want to have my Django project send mail through and an external SMTP server. You can easily set this up by adding the following variables to you settings file.

EMAIL_HOST = 'mail.example.com'
EMAIL_PORT = '25'
EMAIL_HOST_USER = 'test'
EMAIL_HOST_PASSWORD = '******'
DEFAULT_FROM_EMAIL = 'test@example.com'
SERVER_EMAIL = 'test@example.com'

comments

create relative paths for your django settings Mar
22
1
0

I wish Django used this by default, but you should be setting up your project using relative paths in your settings. By not hard coding your paths makes your project easier to manage.

Start by setting a variable to use as the base that pulls it's path dynamically through os.path; I use PROJECT PATH.

import os

PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))

You can then append to the PROJECT_PATH variable when setting up your other paths that are based on your project's root path.

MEDIA_ROOT = PROJECT_PATH + '/media/'

TEMPLATE_DIRS = (
    PROJECT_PATH + '/templates/'
)

comments

broadcast django runserver Mar
22
1
0

Sometimes I need to broadcast a django project through the local network, or even externally, with runserver. This is pretty easy to do, although it should only be only be done for development. Never use runserver for production.

Running it through the local network will allow you to connect to your computer from any other computer on the local network. This is handy for client presentations or IE debugging.

You must first find your inet address. You can do this easily with the <ifconfig> command. After that just initialize runserver by passing it the ip and port (remember to source your virtualenv if needed).

ifconfig

./manage.py runserver 192.168.1.2:8000

If for some reason you need to broadcast runserver externally you can bind it to your external ip, or let automatically detect it like this:

./manage.py runserver 0.0.0.0:8000

comments

mysql cheatsheet Mar
22
1
0

Here's some of the MySQL commands that I regularly use. I'm posting this so I have a place to quickly look these up, but perhaps someone else might find these useful as well.

# login
mysql -u root -p

USE database_name;
SHOW tables;
DESCRIBE table_name 

# create database
CREATE DATABASE django_project;
SHOW DATABASES;

# create user
CREATE USER username IDENTIFIED BY 'pass1';

# grant access
GRANT ALL ON django_project.* TO username;

# Export A MySQL Database
mysqldump -u username -p database_name > FILE.sql
mysqldump --user=XXXXXXXX --password=XXXXXXX -A > /PATH/TO/DUMPFILE.SQL
mysqldump --user=XXXXXXXX --password=XXXXXXX DB_NAME1 DB_NAME2 > /PATH/TO/DUMPFILE.SQL
mysqldump --user=XXXXXXXX --password=XXXXXXXX DB_NAME --tables TABLE_NAME > /PATH/TO/DUMPFILE.SQL

# Import A MySQL Database
mysql -u username -p database_name < FILE.sql
mysql --verbose --user=XXXXXXXX --password=XXXXXXXX DB_NAME < /PATH/TO/DUMPFILE.SQL

LOAD DATA LOCAL INFILE '/importfile.csv'
INTO TABLE test_table
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
(field1, filed2, field3);

# duplicate table
CREATE TABLE newname SELECT * FROM sourcename

# alter table
ALTER TABLE profiles_category ASS header varchar(100) NOT NULL AFTER icon;
ALTER TABLE profiles_category MODIFY icon varchar(100) NOT NULL; modify attributes
ALTER TABLE profiles_category CHANGE icon image varchar(100) NOT NULL;    rename
ALTER TABLE profiles_category DROP icon;

# update table
UPDATE profiles_category SET header='name' WHERE id=1;

comments

automatically dump and load data into django Mar
18
1
0

Django provides and easy way to backup and load data from your project regardless of which storage engine you're using through [dumpdata] and [loaddata]. If you don't provide the application name after the dumpdata command it'll output the data from all installed applications.

If you want the file to be formated for reading, use the [--indent] option.

manage.py dumpdata flatpages --indent=4 > flatpages.json

manage.py loaddata flatpages.json

You can name the dumpdata file [initial_data.json] if you want to automatically load the data file when you [syncdb] and [flush]. It's handy to use with the [--noinput] option to suppress user input if you have an initial_data.json set up.

Be very careful with initial_data.json though as you can unwillingly overwrite data, and you'll be a sad panda. I personally will only locally manage initial_data.json, and will keep it out of the repository at all times.

manage.py syncdb --noinput

manage.py flush --noinput

comments

django singleton Mar
17
1
0

Sometimes I have a django model that I want to behave like a singleton where there has to be one, and only one row present in the table at all times. I accomplish this by overriding the model's save() and delete() methods.

class Singleton(models.Model):
    # put model fields here

    def save(self):
        self.id=1
        super(Singleton, self).save()

    def delete(self):
        pass

comments

delete old files in linux Mar
16
1
0

Edited: 4.15.2010 - fixed typo

You can use the [find] command in linux to remove old files through the command line. Pass in [-mmin +/-num] to specify minutes, and [-mtime +/-num] for days. Use [+] to get items older than the specified times, and [-] for younger.  Filter file/directory names through [-name], and run a command through [-exec].

# remove all files older than 7 days
find /path/to/directory* -mtime +7 -exec rm {} \;

# remove all *.py files younger than 30 minutes
find /path/to/directory* -name '*.py' -mmin -30 -exec rm {} \;

This is tested on Ubuntu.

comments

create xhtml strict external links with jquery Mar
15
1
0

If you're anything like me when coding to the XHTML strict doctype, you get annoyed when things break your validation (Youtube, I'm looking at you). I've seen many a flame war over whether or not to let external links open a new window. It's not my intention to rekindle the flames, so lets just say this: Sometimes you just have to do what the client wants. Besides, who am I to argue? After all it's their site that they are paying me to build.

With that being said, now comes the question about how to allow links to open a new window without breaking your strict validation with the deprecated target="_blank" attribute. I've found that auto-detecting the link with jquery has been a fairly elegant and painless solution.

At this point it's worth noting that the target attribute will no longer be deprecated in HTML5, so our good friend target="_blank" will be back. But until HTML5 is better supported (cough Microsoft) we're going to be stuck with alternate solutions; so let us tarry forth.

The first thing I do is to organize my site so that all internal links are relative, and external links are absolute (starts with http://). With that in place I can then open a new window whenever I detect an href that contains http://.

$('a[href^="http://"]').click(function(event) {
    return !window.open(this.href);
});

That's a nice start, but there are rare occasions where I'd like to open a new window for an internal link, and keep an external link in the same window. For these outliers I override the script by adding a rel="internal" or rel="external" into the <a> tag and handle it with the javascript. So the complete script looks like this:

$(document).ready( function() {
$('a[href^="http://"]').click(function(event) {
if($(this).attr('rel') != 'internal') {
return !window.open(this.href);
}
});

$("a[rel='external']").click(function() {
return !window.open(this.href);
});
});

<a href="/page">stays in the same window</a>
<a href="http://example.com">opens a new window</a>
<a href="/page" rel="external">opens a new window</a>
<a href="http://example.com" rel="internal">stays in the same window</a>

And this will cover 99% of my needs.

comments

convert integer to string inside a django template Mar
15
1
0

Every now and then I come across a situation where I'm required to do an integer to string comparison inside a Django template. I need to unify the data types before I run the comparison or else the equality will fail. This sounds like a job for template filters.

I could write my own int_to_string filter like the following (the @stringfilter converts the argument to a string before it passes the variable into the function).

from django.template.defaultfilters import stringfilter

@register.filter
@stringfilter
def int_to_string(value):
    return value

However, I would then have to load the filters into the necessary templates. Yes, I know it's not hard to do, but I'm lazy. Wouldn't it be nice if there was a pre-built filter that did the conversion for me? Well I'm in luck because the slugify filter does just that.

All I need to do is slugify the integer and compare it to the string variable. It works like a charm because when using slugify on an integer, besides the int to string conversion, it won't transform the data.

{% ifequal my_integer|slugify my_string %}

comments