Monday, November 16th, 2009
Case insensitive usernames in Django
Django's authenticate() method treats both username and password as case sensitive. Password HAS to be, because an uppercase password will not create the same hash as a lowercase password. That is understandable. But the username case sensitivity I don't get. Here is my solution. It requires an extra query to the DB, so if anyone can do this better without actually hacking Django, please let me know.
if loginform.is_valid():
#make usernames caseinsensitive
try:
u = User.objects.get(username__iexact=loginform.cleaned_data['username'])
username = u.username
except User.DoesNotExist:
username = loginform.cleaned_data['username']
user = authenticate(username=username,password=loginform.cleaned_data['password'])
what is happening here is i am querying the user table for a user whose username matches the provided username case insensitively. if there is one, use the actual stored username as the username passed to authenticate(). if there isn't one, just use the provided username, because they will get the same error message saying it doesn't exist.
any better ideas out there?
5:42pm by Brandon //4 comments 1954 views Thursday, October 8th, 2009
Would this work?
Scenario: You have huge database tables with many columns and tons of data. You want to run large reports over all this data and display lots of records at a time.
Suggestion: This popped into my head and I'm curious if it would work or totally over bloat the whole thing. What if you went to the server and got nothing but a list of unique ids to manipulate with javascript, iterate over the list and put an ajax function like jquery.get in there for each id, then use the browser to load each record in the window on document ready?
Small example: You have ten records in the db. You have a view that returns an empty page with a js file and on document ready iterate over a list of all the unique ids 1-10.
Then using ajax, you could load each record into a table or something. Now instead of your entire page having to load all those records from the server before it fires $(document).ready(), you start iterating over this list and you can start loading the content. i think if you used jQuery for this, you could get some really neat effects of the page loading fading in from top to bottom. Would all those hits to the server be too close together for the server to handle? or would putting the function call at the end of the completed $.get() work well?
i know this would work on a ten record report, but if your report had thousands of rows in one view, would this work? seems like most browsers would be able to handle 3000 unique id's pretty easily. i just picture div after div fading in under each other in a really neat wave like effect.
if you know the answer please comment!
main questions: would this destroy the server? pulling one record at a time seems like it shouldn't be a big deal to spit out.
7:52pm by Brandon //comment 1178 views Wednesday, October 7th, 2009
Jquery Comments
I just can't say this enough. jQuery is AWESOME. I had a comment system in a django blog, which has supervisors and above moderate operator comments. With 37 lines of javascript (including comments and organizational line breaks) I was able to moderate the comments inline as shown here:
Inline Comment Moderation
Here is the jquery:
$(document).ready(function(){
change_links('');
});
//found this in some forum. it works for what i need, but is it good?
$.fn.unwrap = function(expr) {
return this.each(function(){
$(this).parents(expr).eq(0).after(this).remove();
});
};
function moderate_click(link){
var comment = link.closest('.comment');
comment.slideUp();
var id = comment.attr('id');
//get publish or remove
var actionurl = link.attr('href');
$.get(actionurl,function(data){
comment.wrap("<div id='one_time_use'></div>");
$('#one_time_use').html(data);
$('#'+id).unwrap("div");
change_links('#'+id);
$('#'+id).slideDown();
});
}
function change_links(param){
//the param gets the comments to change links
//ie either "" or the commentid
$(param + ' .moderate_links a').click(function(){
moderate_click($(this));
return false;
});
}
and here is the important part of the django view:
#this part is in both publish and remove views
if request.is_ajax():
return ajax_comment(request,comment,redirect)
#this is the ajax_comment function
def ajax_comment(request,comment,redirect):
if redirect.find('/bulletins/comments/') != -1:
blogslug = 'comments'
else:
blogslug = ''
return render_to_response('bulletins/comment.html',{
'comment':comment,
'user':request.user,
'blogslug':blogslug,
'is_ajax':True,
})
a call to those more experienced: is this good? is there a way to do this in only 10 lines of code? since i'm mostly teaching myself, i can only go on the basis of "It works!"
11:09am by Brandon //comment 820 views Monday, October 5th, 2009
Best Complete Sentence Ever
"Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo."
Essentially say "People I hate hate other people."
Now describe the people. "Maine people I hate hate other Maine people."
Now I'm not the only one, and I'm from Maine. "Maine people Maine people hate hate Maine people."
Now replace the descriptors with Buffalo (the place as an adjective of position), the people with buffalo (as in herd of), and the action with buffalo (the verb meaning: to bully).
"Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo."
wikipedia on this sentence.
2:16pm by Brandon //comment 426 views Thursday, October 1st, 2009
Screentoaster.com
This is a fantastic tool.
screentoaster.com
You sign up, the browser loads a java applet, and before you know it you can record in full screen or in a rectangular section. Perfect for showing friends, coworkers, and grandma how set up her gmail account.
the best part about it is that it's entirely web-based and incredibly user friendly. you click a button or alt-s to start and pause recording, then after clicking "stop recording" you have the option to upload to youtube, upload straight to screentoaster (which gets through my work's internet filter as opposed to youtube), or create a .mov file.
have fun with it. i bookmarked it immediately.
12:35am by Brandon //comment 409 views Friday, September 18th, 2009
Django 1.0 Website Development
I recently received a message from someone at Packt Publishing regarding the new book Django 1.0 Website Development. She gave me an opportunity to check out the book in pdf version, and I really liked it. It's a great tutorial that runs through a neat project for beginner to experienced Django programmers.
I've been using Django for almost a year now, and throughout the book even the topics I knew already were not boring. I even picked up a few ideas and got some tips that I will use on my project for work!
This book explains in detail many of the pieces of Django that aren't even in Django's own documentation. The Django messages feature and how to use Django's built in comments system are just two places where I've always had to write my own, because I couldn't find enough details on how to use the built in ones.
Besides a few errors where the text didn't match the code examples, I give this booktorial an 'A'.
This book from Packt Publishing has made me look into this book: Expert Python Programming. I think it could really help fine tune my programming skills especially with Python which is my programming language of choice as of late.
10:21pm by Brandon //comment 1235 views Monday, August 17th, 2009
Django Templates and Dictionaries
Ever needed to access a python dictionary from a django template? It's pretty straightforward:
{{dictionary.key}} will get you that.
but ever needed to do it inside a loop, with a variable key? django will not allow you to do this default (after finding a solution that worked, i can't BELIEVE that it isn't a part of django already. maybe it is in the new version?)
anyway, i wrote a custom template tag which allows me to access the keys of a dictionary using a variable:
from django import template
register = template.Library()
def dict_get(value, arg):
#custom template tag used like so:
#{{dictionary|dict_get:var}}
#where dictionary is duh a dictionary and var is a variable representing
#one of it's keys
return value[arg]
register.filter('dict_get',dict_get)
now, {{dictionary|dict_get:var}}, where var is one of the dictionary keys, will give me exactly what i want.
update:
there is a big difference that i didn't make obvious in my post.
in view:
dict = {'1':True,'3':False,'5':True}
arr = [1,2,3,4,5]
in template:
{{dict.5}} #evaluates to True
{% for key in arr %}
{{dict.key}} #does not work
{{dict|dict_get:key}} #WORKS!
{% endfor %}
12:35pm by Brandon //comment 2158 views