fixing jquery ajax caching Jun
16
1
0

Depending on browser settings you might run into problems with caching when calling pages through AJAX. I've run into issues with WebKit based browsers (Chrome, Safari) as it seems they are more aggressive with their caching than Firefox and even IE. This was one of the few times where something worked in IE and not Safari.

If your ajax is calling a dynamically generated page where its content changes over time you need to disable caching on the AJAX call.

In JQuery you can just set the cache parameter to false:

$.ajax({
  url: "/path/to/page/",
  type: "POST",
  cache: false,
  success: function(data){
    ...
  }
});

Another technique that you can do is to generate a random variable on each call to the end of URL to trick the browser.

$.ajax({
  url: "/path/to/page/?v=" Math.ceil(10000*Math.random()),
  type: "POST",
  success: function(data){
    ...
  }
});

comments

create/export and load/import csv files with mysqldump in mysql May
27
1
0

I'm often asked to create csv files to import into other applications. If you're using MySQL it's handy to be able to create a CSV on the fly with mysqldump. This is easily achieved with the following command:

mysqldump -u <user> -p --tab=<directory> --fields-enclosed-by='"' --fields-terminated-by=',' <database> <table>

This creates a .sql dump file and a .txt csv in the directory that you specified with [--tab]. The second part of this operation (the .txt csv creation) will be performed by the MySQL user, so it'll need to have write permissions in the [--tab] directory. Also, the mysql user needs to have the appropriate permissions (I believe it's the FILE privileges).

Alternatively you can import a csv into the database with the following command while logged into the mysql shell using the appropriate database:

LOAD DATA LOCAL INFILE '/path/to/my.csv' INTO TABLE <table>
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
(<field1>, <field2>, <field3>);

comments

auto-populate subject and body line in mailto link May
21
1
0

Sometimes I need to auto-populate the subject and body lines inside a mailto link. All you need to do is attach the <subject> and <body> as GET variables.

<a href="mailto:test@example.com?subject=Your subject goes here.&body=Place the body text here.">Send me an email</a>

You can omit the email address if you want the user to be able to choose who she wants to send this to.

<a href="mailto:?subject=Your subject goes here.&body=Place the body text here.">Send me an email</a>

comments

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