testing 404 500 error pages in django development envirnoment with django-cms May
18
1
0

It's nice to be able to test your 404.html and 500.html templates in your development environment before you push to production.

You could use direct_to_template, but it would be better to use the default Django views that the errors actually use. These are "django.views.defaults.server_error" and "django.views.defaults.page_not_found". All you need to do is to add these to your urlpatterns in a conditonal statement for local development. *** note the += ***

# urls.py

urlpatterns = patterns('',
    ...
)

if settings.LOCAL_DEV:
    urlpatterns += patterns('',
        (r'^404/$', 'django.views.defaults.page_not_found'),
        (r'^500/$', 'django.views.defaults.server_error'),
        (r'^media/(?P.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT} ),
    )

If you're using Django-CMS this is not going to work because the cms page middleware will call the 404 error before it gets to the LOCAL_DEV urls. This is easily fixed by moving the cms url include to after the LOCAL_DEV urls.

urlpatterns += patterns('',
    url(r'^', include('cms.urls')), # put this near the end
)

comments

css3 border radius May
18
1
0

I keep having to look up the definitions for CSS border radius when it comes to supporting the Mozilla and Webkit specific styles. I'm pasting this here for easy reference.

-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;

-webkit-border-top-left-radius: 6px;
-webkit-border-top-right-radius: 6px;
-webkit-border-bottom-right-radius: 6px;
-webkit-border-bottom-left-radius: 6px;

-moz-border-radius-topleft: 6px;
-moz-border-radius-topright: 6px;
-moz-border-radius-bottomright: 6px;
-moz-border-radius-bottomleft: 6px;

border-top-left-radius: 6px;
border-top-right-radius: 6px;
border-bottom-right-radius: 6px;
border-bottom-left-radius: 4px;

comments

limit character entry with jquery May
18
1
0

It's common to need to limit character count on user input fields. There's a lot of plugins that you can get this to do it for you. However, when possible I like to reduce the amount of third party scripts. The basic concept is pretty simple to follow in JQuery.

Lets say you have HTML like the following:

<div id="limit"></div>

...
<textarea name="comment" cols="40" rows="10" id="comment"></textarea>
...

You can then bind a keypress event that checks the lengh of the value on the input or textarea.

$('#comment').keypress(function() {
    var MAX_CHAR = 140 - 1;

    $('#limit').text('Characters remaining: ' + ((MAX_CHAR + 1) - $(this).attr('value').length));

    // limit entry
    if($(this).attr('value').length > MAX_CHAR) {
        this.value = this.value.substring(0, MAX_CHAR);
    }
});

This script prints out how many characters are left in the <div id="limit"> and limits the user to inputing 140 characters. No plugins necessary.

Limiting input on the front end is only a convenience for the user. If this functionality is important for your application make sure to make the proper checks and sensitization on the backend when processing the form.

comments

call slugify template tag in django model or view May
17
1
0

Edited: 6.1.2011 - fixed typo

Sometimes I need to slugify something within a django model or view file. Django already has this functionality written as a template filter, and you can reuse this outside of the templates. You can import slugify into your python code like so:

from django.template.defaultfilters import slugify

slugify(<value>)

Which then allows you to write something like:

class Custom(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(blank=True) def save(self): self.slug = slugify(self.name) super(Custom, self).save()

However, if you need this type of functionality depending on your situation it might be easier to set this up using the django admin prepopulated_fields option.

# models.py
class Custom(models.Model):
    name = models.CharField(max_length=100)
    slug = models.SlugField()


# admin.py
class CustomAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug': ('name',)}

admin.site.register(Custom, CustomAdmin)

This will auto-populate the slug field while you type the name within the django admin.

comments

social network share link cheatsheet May
11
1
0

Here's some of the common social networks and their associated share link formats. They are all similar, but of course there's no standard . . . that would be too easy.

These are subject to change at any time. Please let me know if I've missed something.

<!-- twitter -->
<a href="http://twitter.com/home?status={{ title }}
{{ request.build_absolute_uri }}" title="Click to share this post on Twitter">twitter</a>
<!-- twitter -->

<!-- facebook -->
<a href="http://www.facebook.com/share.php?u={{ request.build_absolute_uri }}&t=<title of content>">facebook</a>
<!-- facebook -->

<!-- reddit -->
<a href="http://www.reddit.com/submit?url={{ request.build_absolute_uri }}&title={{ title }}">reddit</a>
<!-- reddit -->

<!-- digg -->
<a href="http://digg.com/submit?url={{ request.build_absolute_uri }}&title={{ title }}&bodytext={{ description }}">digg</a>
<!-- digg -->

<!-- delicious -->
<a href="http://delicious.com/save?url={{ request.build_absolute_uri }}&title={{ title }}">delicious</a>
<!-- delicious -->

<!-- myspace -->
<a href="http://www.myspace.com/index.cfm?fuseaction=postto&u={{ request.build_absolute_uri }}&t={{ title }}
&c={{ contetent }}">myspace</a>
<!-- myspace -->

<!-- stumbleupon -->
<a href="http://www.stumbleupon.com/submit?url={{ request.build_absolute_uri }}">stumbleupon</a>
<!-- stumbleupon -->

<!-- linkedin -->
<a href="http://www.linkedin.com/shareArticle?mini=true&url={{ request.build_absolute_uri }}&title={{ title }}
&summary={{ description }}&source={{ source }}">linkedin</a>
<!-- linkedin -->

<!-- google bookmarks -->
<a href="http://www.google.com/bookmarks/mark?op=add&bkmk={{ request.build_absolute_uri }}&title={{ title }}">google bookmarks</a>
<!-- google bookmarks -->

comments

smtp django settings May
11
1
0

I have to go trolling the internet every time I need to locate the default email variables that I need to set up the SMTP connection the settings file for Django, so I'm throwing them here for reference. Perhaps someone else might also find this useful.

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

comments

get all users in a group in django May
10
1
0

There's a couple of ways to get the list of all users in a group in Django.

First, you should include the User and Groups class from django.contrib.auth (I'm going to assume you have this included in INSTALLED_APPS or else you wouldn't be here).

from django.contrib.auth.models import User, Group

Then you can do:

group = Group.objects.get(name='blogger')
users = group.user_set.all()

or

User.objects.filter(groups__name='blogger')

or if you want to get fancy

perm = Permission.objects.get(codename='blogger')
users = User.objects.filter(Q(groups__permissions=perm) | Q(user_permissions=perm) ).distinct()

comments

getting the browser's scroll position with javascript May
09
1
0

Sometimes you need to dynamically detect the browser's scroll position. Dealing with browser inconsistencies is a PITA, but here is a javascript function that I use that gets the job done.

function getScrollXY() {
    var x = 0, y = 0;
    if( typeof( window.pageYOffset ) == 'number' ) {
        // Netscape
        x = window.pageXOffset;
        y = window.pageYOffset;
    } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
        // DOM
        x = document.body.scrollLeft;
        y = document.body.scrollTop;
    } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
        // IE6 standards compliant mode
        x = document.documentElement.scrollLeft;
        y = document.documentElement.scrollTop;
    }
    return [x, y];
}

You can then call it like so:

var xy = getScrollXY();
var x = xy[0];
var y = xy[1];

comments

iterate over a dictionary inside a django template Apr
27
1
0

The official Django documents how to iterate over a dictionary inside a for loop, but I sometimes forget. I'll attempt to do something like this:

{% for key, value in data %}
    {{ key }}: {{ value }}
{% endfor %}

but will fail miserably. The key to extracting a dictionary inside django templates is the items dictionary function, which "Return a copy of the dictionary’s list of (key, value) pairs".

This allows us to loop through the dictionary using items like so:

{% for key, value in data.items %}
    {{ key }}: {{ value }}
{% endfor %}

comments

removing, changing, and controlling emacs backup files Apr
21
1
0

The default functionality of how emacs handles its backup files annoys me. I don't like how it clutters my folders by leaving a trail of ~ files wherever I go. If you're in the same camp there's a couple of things you can do about it.

You can clean up existing your directories by removing backup files by any number of ways. I like to use one of these commands:

#  from anywhere
find /path/to/directory -name '*~' -exec rm {} \;

# from a directory
rm -rf *~

Then you can either change the backup directory so all files are stored in a common location:

;; add to .emacs file
'(backup-directory-alist (quote (("." . "~/backup/path"))))

or prevent emacs from making backup files in the first place:

;; add to .emacs file
(setq make-backup-files nil) 

comments