Django — How to get only the data from a form field

Say you can’t be using {{ form.myfield }} because you need full control over the input tag. All is fine & well except for when your form requires validation and you need initial values set for your fields.

I looked through some tutorials & couldn’t find what I was looking for. Here’s the big secret:

{{ form.myfield.data }} = the value associated with that key.
Enjoy.

Jquery — Not to fear, Firebug causes Extreme Firefox Slowness

At first I was worried that I simply had “too many elements” and jquery was dying on me. Then I found out that Firebug causes problems on firefox. All animations are very heavy and “low-frame-rate”.

It works just fine on Konqueror. I can only hope its fine otherwise : ).

Who uses firebug anyways? The same very small crowd who might turn off javascript.

Jquery — Pull Data From Form Input Field

I’ve had a few problems with jquery where the resources I come across on Google are a little old or something.

My version is 1.2.6

The two issues I had were: passing onComplete parameters to the built in slideUp, slideDown functions & getting data from a form input field.

For slideUp, slideDown, a visit to the docs helped in that you no longer specify onComplete at all.

For grabbing data from a form field, a ton of random searches revealed it is $(“mydiv”).val();

Its .val()

I had seen examples with fieldValue(), and value but neither worked. Here it is!

Design vs e-Commerce Conversion Rates

This is a very rough post. I can’t really focus on making this coherent, but it is simply important I get it written.

e-Commerce is amazing because one can quantify the effect of having two add to cart buttons, or the effect of a certain color on the text. Studies show that two buy icons increase conversion rates by 4%. Studies also show that showing the same link twice increases its effectiveness by a ridiculous margin. Nowhere else can you get information so precise. You couldn’t determine how much more sales a paper ad generated. In fact, you can only have a rough idea what traditional advertising did for your immediate sales.

Anyways, I have been piecing it all together through my intuition. What is perfect, in my eyes? But this article just gave me a few pointers. I had made icons for the small “add to cart” elements, but not a big icon like amazon.com.

And I must admit, they do it nicely. The cart is always accessible and you are ever so reminded of checking out. Using that bar would allow me to include lots of other information as well, such as how many are left, how much you are getting discounted today, etc. how much more you can buy & get further discounts.

http://www.grokdotcom.com/2008/02/26/amazon-shopping-cart/

I think this site may turn out to boast great conversion rates after it goes live. I just have much to do programming still. The last step is the fine-tuning of the design.

So, what I have to remember to do is to do a javascript CSS switch to a pure white version of the site. It might be too blinding for others. Ironic, no? that black is the blinding one?

It would also be ideal to have re sizable text, but that is royally difficult to coax into a layout.

Django — My hideous pagination solution. Help required.

I need help with pagination. My problem is that I need pagination on nested lists. If anyone can help me here I would greatly appreciate it.

Given list [ [1,2,3],[4],[5,6]], I need a way to paginate & spit back partial lists. I have categories, and products in those categories. If user wants to see all products in the “red-wine” category, the paginator needs to paginate products over several child categories.

Category “Red-Wine” might have child category “Malbec” which has 10 products, and category “Bonarda” which has 3 products. If I set number per page at 11, I need the full Malbec category and Bonarda with only 1 product.

In my example below I end up flattening the entire Red-Wine category list to a single list with all products.
I paginate that list, and THEN re-create the category structure. It looks terrible.

Flattening the category list:
data = list(category.product_set.all())
for cat in category.get_all_children():
 data.extend(cat.product_set.all())

This gets all products related to the main category.

Now I need to paginate that flattened list by some number defined in the url:
p = Paginator(data, paginate_by)

Then, to have category names show up in groups in the template (as opposed to for each product), like so:
Category1
Product1
Product2
Category2
Product3
Category3

I wrote some disgusting stuff to paginate into categories.
I made a class to fake a category + children products.

class cat():
 def __init__(self, category, products):
  self.category = category
  self.products = products

Then, a loop to find which products are children of what and re-create the Category -> category.product_set structure of the original queryset.

temp =[]
result = []
for product in page.object_list #(this is the paginated and flattened list of objects)
 if product.main_category not in temp:
  temp.append(product.main_category)
  product_group = []
  for prod in page.object_list:
   if prod.main_category == product.main_category:
    product_group.append(prod)
  result.append(cat(product.main_category.name, product_group))

which leaves you with something that you can use in a template like:
{% for cat in category %}
{{ cat.name }}
{% for product in cat.product %}
{{ product.name }}
{{ product.image }}
{% endfor %}
{% endfor %}

It works, but I suspect it is very inefficient. Any solutions?
Should I doing something more like checking the amount of products in each category and only modifying the last category that must be split into smaller groups?

Paginate_by = 2
len(category_1) = 1 # check, keep as is.
len(category_2) = 5

now split category_2?

Django — Saving Arbitrary Data to Model Instances

I kept having troubles with duplicate queries (where the exact same DB query is used more than once in a page view) because I had failed to save the data in the instance.

I had a “Product” model & a “Price” model where one Product can have many prices (QTY discounts).

I had written a quick method to retrieve the base price by filtering the related Price models:
def get_base_price(self):
 return self.price_set.filter(quantity=1)[0]
main_price = property(get_base_price)

But other methods that used “main_price” kept requiring get_base_price to hit the DB again. I didn’t realize that having main_price defined in the model doesn’t save the information in the model. That was what I had intended by doing main_price = property(get_base_price) but was quite a worthless attempt.

Magus helped me out on IRC and I ended up with :

def get_base_price(self):
 if not hasattr(self, 'price'):
  try:
   self.price = decimal.Decimal(self.price_set.filter(quantity=1)[0])
  except IndexError:
   return 'no price'
 return self.price
unit_price = property(get_price)

Where if self.price is not set, it queries the database and gets the data. Looks like I previously thought I was saving the data by defining unit_price in the class. Nope!

Something strange that I don’t understand is when referring to the above saved data from another method.

Assuming we set self.price as above, and unit_price = property(get_price) which returns self.price, this doesn’t work:

def some_other_method(self):
 print self.unit_price # doesn't work

While this does:

def some_other_method(self):
 unit_price = self.unit_price
 print unit_price # works

Maybe somebody can enlighten me here on why that is so.

Anyways, thanks to Magus, I’ve lessened some queries and I’m not as reluctant to define model methods that had previously caused duplicates. Great!

Next I’m working on paginating my product views & keeping the query size down.

Japan

Met with a great guy named Tom today. In fact, everyone in the group was very cool. I had missed being surrounded by this type of crowd.

Tom is the first guy I’ve met who knows much about Japanese culture, and understands the differences in the ways of life vs American (er, western?) life. The fundamental values of everything are different.

I could speak for ages about this, but the most important thing that came out of tonight is this:

I should go to Japan, and learn all about it. For 1: It makes financial sense. Japan is the 3rd largest economy in the world. That’s fucking huge. Japan is a ‘hard to grasp’ market with incredible reward potential. Another way to think about this is such: America breeds ridiculous amounts of entrepreneurs. There are products sold left and right. Japan breeds no such thing. Life is more about other things than making the big bucks in any way possible. But thats precisely an advantage for me. Why not make use of this tremendous asset I have instead of throwing it away in a b attlefieldwhere it doesn’t matter?

Tom also kept suggesting I go back to japan for myself. I’ve always shunned my Japanese side (which is entirely, utterly different from my American personality) because it showed me a world that could not be shared with the rest of my life (American friends). This I find very depressing, much like how I think of academia, or at least what I call academia.

For example, politics scares me quite a bit because it matters less who’s right than who’s marketing the best (or who has the most money TO market & pay for PR professionals and mass analysis). In this world, truth, or “who’s right” matters not. People will continue to believe what they want to believe. One great example I came upon recently was a documentary film maker who wanted to show the world how utterly ridiculous Vampires are. That Dracula is named after somebody with absolutely no association to blood sucking people. Yet this film maker was extremely discouraged and stopped filming. Why? Because he realized that publishing this documentary (even with such absolute evidence) would only serve to create MORE believers.

How does this relate? Because so many things I care about don’t matter. Knowing the truth means nothing. It has no impact on the world outside academia. I have been afraid to embrace my Japanese side because my entire life until now does not relate to it. I would be completely distancing myself from my previous life, because nobody would ‘get it’. That was scary. Now, though, I realize that it is quite an asset.

I can only imagine what kind of trust I could develop with Japanese business partnerships that would be largely impossible for others.

So Japan it is. Perhaps very soon. Perhaps not. But thinking about this in terms of Anuva is very important.

After all, my mom’s friends all see the magic and beauty in it. Having 6 bottles to choose from. Which will I choose? Its all great fun. But I have no idea how marketing works there, and I need to live there to figure it out. The most challenging is to learn how to speak professionally in Japanese. I can pick up on the social cues, but I can’t speak in response to them. There are words never used in casual speech that I have no way of knowing, like: “cost analysis”, “projection”,”business plan”,”profit margin”,”operating expense”.

Lots to learn, and hope that Japan doesn’t crumble in the meantime.

Python — Basics of Python Dictionary: Looping & Sorting

Here some bits of info about python dictionaries & looping through them.

Extra special beginner stuff.

What is a dictionary?

A python dictionary is an extremely useful data storage construct for storing and retreiving key:value pairs.

Many languages implement simple arrays (lists in python) that are keyed by a integer. For example, if you made a list [1, 2] – the first value would be retrieved via [1, 2][0].

my_list = [1, 2, 3]
my_list[0]
# Out: 1
my_list[1]
# Out: 2

A dictionary is a little more advanced in that the keys can be many other things than integers. Often times the key will be a string merely for the fact that it’s easy for a human to recall.

Will I remember that my_list[3] is my phone number? Not nearly as well as if I have a key named “phone_number”.

my_dict = {
	'key1': 'value1',
	'key2': 'value2',
	'key3': 'value3'
	}
my_dict['key1']
# Out: 'value1'

Major differences vs lists

– Keys are any hashable object (say strings for simplicity)
– Are NOT ordered (a list is by definition ordered)

One way I like to think about them are as little variable containers. The fact that they are wrapped in a container makes them quite useful and versatile since you can easily move the “container” around.

In fact, variables are very much related to dictionaries! Whenever you declare a variable (x=3), that variable is accessible by its string name (‘x’) via the dictionary returned by the builtin function ‘locals()’ or ‘vars()’.

Watch and see:

var1 = 'val1' # local variable definition
var2 = 'val2'

locals_dict = locals()
print locals_dict['var1']
# Out: val1

container = {}
container['var1'] = 'val1'

print container['var1']
# Out: val1

Looping through dictionaries

Now, if you did a little experimenting, you would see that if you loop through a dictionary you loop through its keys.

>>> my_dict = {
...     'key1': 'value1',
...     'key2': 'value2',
...     'key3': 'value3'
...     }
>>> for item in my_dict:
...     print item
... 
key3
key2
key1

Note that this is the equivalent of looping through “my_dict.keys()”

What about getting the values?

Based on what we’ve learned, you could always use the keys you are iterating through to pull the value from the dictionary.

for item in my_dict:
    print my_dict[item]

But there are better ways to get the values. Enter the “items” function.

We can ask the dictionary to return key, value pairs via the “items()” function.

for key, value in my_dict.items(): # returns the dictionary as a list of value pairs -- a tuple.
    print key, value

More efficient dictionary loops

Calling “my_dict.items()” requires generating the entire list of key-value pairs in-memory. Sometimes, if your dictionary is too large, this can be a severe performance bottleneck. To get around this problem we can create a generator via the “iteritems()” method.

A generator allows you to iterate one item at a time. Only the key and value are pulled into memory for every iteration and immediately discarded. There are methods for returning a key generator and value generator as well.

for key, value in my_dict.iteritems():
    print key, value

for key in my_dict.iterkeys():
    print key
    
for value in my_dict.itervalues():
    print value

Note that one thing you can’t do with a generator is to delete a key during the generator loop.

for x, y in mydictionary:
    del mydictionary[x] 
    # Out: RuntimeError: dictionary changed size during iteration

Sorting a Python Dictionary

Actually, python dictionaries can’t be sorted. We will have to turn them into lists to sort them.

    
# to my dictionary...
sorted_list = [x for x in my_dictionary.iteritems()] 

sorted_list.sort(key=lambda x: x[0]) # sort by key
sorted_list.sort(key=lambda x: x[1]) # sort by value

# to reverse the sort
sorted_list.reverse()

Useful dictionary tips

Accessing a dictionary key that might not exist

Sometimes we know that a dictionary key might not exist. This happens a lot in loops where we don’t want to use a try/except block just to capture the exception.

For these situations we have the “get” method. Pass in the key as the first argument, and it will either return the value or None.

Pass in a second argument, and if the key doesn’t exist, it will return the second argument.

dict_ = {'key1':'value1'}
dict_.get('key1')
# out: 'value1'

dict_.get('key2')
# out: None

dict_.get('key2', "Key doesn't exist")
# out: Key doesn't exist

Get or insert into a dictionary if key doesn’t exist

Sometimes we need to insert a value if the key doesn’t exist in a dictionary. The previous “get” method only returns a value – the dictionary is unchanged.

dict_ = {}
dict_.setdefault('key1', 'value1')
# Out: value1

print dict_
# Out: { 'key1': 'value1' } 

This can be extremely useful if you need to append to a list if it exists or otherwise create a blank list.

key_value_pairs = [
    ('key1', 'value'),
    ('key1', 'value2'),
    ('key1', 'value3'),
    ]
dict_ = {}

for key, value in key_value_pairs:
    dict_.setdefault(key, []).append(value)

print dict_
# Out: { 'key1': ['value','value2','value3'] }

Generate a dictionary from tuples

It’s often useful to generate a dictionary from a list of tuples. For example, you could use a list comprehension to create a dictionary!

key_value_pairs = [
    ('key1', 'value'),
    ('key2', 'value2'),
    ('key3', 'value3'),
    ]

# now let's generate the same list of tuples via list comprehension 
key_value_pairs = [('key{0}'.format(x), 'value{0}'.format(x)) for x in range(1, 4)]

dict_ = dict(key_value_pairs)
print dict_
# Out: {'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}

Conclusion

I’m a little surprised that this is one of my most visited blog posts.
It’s not written well, and it was written years ago!

Let me know if I can improve it… 😉

Django — List all fields in an Object

The last extremely simple post about “How to get the object instance primary key in Django” reminded me of something.

Listing all model fields in a django model instance

for field in model_instance._meta.fields:
    print field.name

model_instance._meta.get_field('field_name') # if you want one field    

Listing all attributes in a python object

Similarly, ever have a random object that you don’t know the fields of?
Or ever not remember whether your field/method/attribute was called short_description or shortdescription?

Use the built in dir() function.

dir(model_instance)

Django — Get an objects Primary Key

Somebody asked on #Django IRC: what is an easy way to get an objects primary key? I was shocked to hear he couldn’t find it on google.. and I guess it’s true. This is probably the very first stepping stone in learning Django.

I say: Do the Django Tutorials, they are short, well written, and fun!
Besides, its got a hassle-free return policy (90 days).

Well, uh…
object_instance.id = your primary key

Wait… I was wrong. here’s an update from SmileyChris:

Actually, object_instance.pk would be more correct. “id” is just the default primary key field, whereas “pk” is an alias to the field which is defined as the primary key.