Pages: 1 2 3 >>

Monday, November 16th, 2009

Case insensitive usernames in Django

Categories: Computers

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?

permalink 5:42pm by Brandon //5 comments 2507 views

Thursday, October 8th, 2009

Would this work?

Categories: Computers

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.

permalink 7:52pm by Brandon //comment 1298 views

Friday, September 18th, 2009

Django 1.0 Website Development

Categories: Computers, Website

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.

permalink 10:21pm by Brandon //comment 1377 views

Monday, August 17th, 2009

Django Templates and Dictionaries

Categories: Computers, Work

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 %}

permalink 12:35pm by Brandon //comment 2492 views

Monday, July 27th, 2009

django blog project

Categories: Computers, Work, Website

i'm developing a django blog here: http://brandons.homeip.net/

right now it has only it's very core. i need to skin it, and add a few features. probably most of the posting i do will be test posts over there.

thanks.

permalink 10:53pm by Brandon //comment 2721 views

Friday, July 17th, 2009

Almost Done

Categories: Computers, Work

I think that I am done modeling my models file for a new project. Can you see where this is going? Is it stupid? Are there other (better) ways to do this? Let me know in the comments please.

-Brandon

#this app started on 7/14/09

from django.db import models
from django.contrib.auth.models import User, Group
from django.contrib.localflavor.us import models as usmodels
from datetime import datetime

class Client(models.Model):
    #choices for the time_zone
    TIME_ZONES = [
        (1,'Eastern'),
        (2,'Central'),
        (3,'Mountain'),
        (4,'Pacific'),
        (5,'Alaska'),
        (6,'Hawaii'),
    ]

    clientID = models.IntegerField(unique=True) #the main account number
    name = models.CharField(max_length=255)
    location = models.CharField(max_length=255,blank=True,null=True)
    contact_number = usmodels.PhoneNumberField(null=True,blank=True)
    contact_email = models.EmailField(max_length=255,null=True,blank=True)
    time_zone = models.IntegerField(choices=TIME_ZONES,blank=True,null=True)
    active = models.BooleanField()
    
    def unicode(self):
        return "%s - %s" % (self.clientID,self.name)
    
    class Meta:
        ordering = ['clientID',]

# Create your models here.    
class Answer(models.Model):
    answer = models.CharField(max_length=255)
    active = models.BooleanField()
    """
    weight will be a percentage of the related topic's value
    (ie a weight of .5 on a topic with a value of 10 = a score of 5/10)
    with the exception of these hard-coded weights
    -3 will give Fail behavior (0/possible)
    -2 will give Pass behavior (scored/possible i.e. ignored)
    -1 will give NA behavior (0/0 i.e. ignored)
    """
    weight = models.FloatField(help_text="Percentage of Topic Value <br/>\n-3=auto zero, -2=ignored, -1=ignored")
    
    def unicode(self):
        return "%s : %s" % (self.answer,self.weight)
        
    class Meta:
        ordering = ['-weight',]
    
class Section(models.Model):
    name = models.CharField(max_length=255)
    
    def unicode(self):
        return self.name
    
    class Meta:
        ordering = ['name',]
    
class Topic(models.Model):
    section = models.ForeignKey(Section)
    topic = models.CharField(max_length=255)
    description = models.TextField(null=True,blank=True)
    value = models.FloatField()
    active = models.BooleanField()
    possible_answers = models.ManyToManyField(Answer,related_name='possible_answers')
    default_answer = models.ForeignKey(Answer,related_name='default_answer')
    
    def unicode(self):
        answers, div = '', ''
        for answer in self.possible_answers.all():
            answers = answers + div + answer.answer
            div = '/'
        return "%s: %s - %s (%s)" % (self.section.name, self.topic, self.value, answers)
        
    class Meta:
        ordering = ['section','-value','topic',]
    
class Questionnaire(models.Model):
    name = models.CharField(max_length=255,unique=True)
    active = models.BooleanField()
    topics = models.ManyToManyField(Topic)
    
    def unicode(self):
        return self.name
        
    class Meta:
        ordering = ['name',]
    
class TopicOrder(models.Model):
    questionnaire = models.ForeignKey(Questionnaire)
    priority = models.IntegerField(help_text="'1' is first listed")
    section = models.ForeignKey(Section)
    
    def unicode(self):
        return "%s: %s" % (self.priority,self.section)
        
    class Meta:
        ordering = ['questionnaire','priority']
    
class ScoreCard(models.Model):
    operator = models.ForeignKey(User,related_name='Operator')
    evaluator = models.ForeignKey(User,related_name='Evaluator')
    client = models.ForeignKey(Client)
    call_time = models.DateTimeField()
    input_time = models.DateTimeField()
    notes = models.TextField()
    possible = models.FloatField()
    scored = models.FloatField()
    percentage = models.FloatField()
    questionnaire = models.ForeignKey(Questionnaire)
        
    def unicode(self):
        return "%s - %s/%s" % (self.operator.name,self.scored,self.possible)
        
class SelectedAnswer(models.Model):
    scorecard = models.ForeignKey(ScoreCard)
    topic = models.ForeignKey(Topic)
    answer = models.ForeignKey(Answer)
    
    def unicode(self):
        return "%s - %s" % (self.topic,self.answer)
permalink 11:58pm by Brandon //comment 2028 views

Saturday, June 6th, 2009

i love jquery

Categories: Computers, Work, Website

this is the beginning of a beautiful relationship!

permalink 1:31am by Brandon //comment 1212 views

1 2 3 >>


©2010 by Brandon Contact design by brandonh

Credits: blog engine | cheap hosting | adsense

visits: stats