Vim Is Wrong

I just saw this post on Stack Overflow about some clever vim commands and as a vim user  I was glad to learn some new tricks I can use.  Then I read the reddit comments about the story and found this (screencapped in case that link changes):

When writing software the code is written once but probably read dozens of times.  Therefore, readable code is very important.  This is one of the central tenets of Python.  These commenters are debating whether readability is equally as important with Vim commands as it is in programming languages.

Previously I would have sided with the advocates of Vim’s terse command syntax without much thought.  Short commands are easier to type and can be more effective.  However, this thread made me reconsider.  Because of Vim’s terse commands, they are harder to learn and to remember.  And once a command is learned, it may be learned as a magical incantation and not a sequence of instructions, so the components won’t be learned and reused for other needs.  So unless a Vim user spends a considerable amount of time learning commands, they’ll be using the editor inefficiently and getting less done than they could because of Vim’s terse commands and steep learning curve.  I’m no longer sure that the efficiency gained by having short, easy to type commands is worth the efficiency lost by having a large set of hard to remember commands in your brain, and an equally large set that you aren’t using because you don’t know them.

Python has a relatively small syntax.  Most things are explicit so there aren’t a bunch of implicit things you have to remember to know what your code is doing.  The advantage that gives a developer is that they can write code more quickly without having to look up syntax rules or function calls all the time.  Also, a new developer can come to the code and will understand the program more quickly with fewer things to learn.  As I thought about Vim’s command complexity, it occurred to me that we already have a command set that’s easy to write, read, and remember, and it’s quick and easy to write a short script like the one in that Stack Overflow comment: Python!  Why can’t Vim use Python to edit the working document?  The Python scripting support is a good start for complex add-ons, but why not make it even more integrated with things like :find(‘query’) instead of /query?  I’m very curious if a readily accessible, full blown python interpreter would make my vim use more effective.

P.S.  Emacs? </blasphemy>

Get The Display Name Of A ModelChoiceField’s Selected Value in Django

I just had a formset where each form had a pre-loaded ModelChoiceField, and I needed to display the name of the selected choice in the template.  On a model you would just use the get_FOO_display() method, but a form has no such convenience.  I found a number of almost solutions on Stack Overflow, and after poring over them I concluded the best solution for my problem was to add the following method to the form:

class QuestionLanguageForm(forms.Form):
    ''' basic QuestionLanguage form '''
    language = forms.ModelChoiceField(queryset=Language.objects.all())
    short = forms.CharField()
    place_holder = forms.CharField()
    long = forms.CharField(widget=forms.Textarea(attrs={'rows':None, 'cols':None}))

def get_language_name(self):
    ''' returns the name of the selected language '''
    try:
       return Language.objects.get(id=self.initial['language']).name
    except:
       return None

This way I can use

{{ form.get_language_name }}

in my template and it prints the human readable name of the language set in my initial data.  This code is not robust; I catch all exceptions and ignore them because I’m only using it in a circumstance where this code won’t raise an exception (and in case it does, at least it won’t fail catastrophically).  However proper error handling could be added pretty simply.  #ExerciseForTheReader

P.S.  The title says “selected” value but I’m actually using a pre-loaded value, not anything user selected.  If you need to get a user selected value you could use self.data or self.cleaned_data instead of self.initial.

Convert Django Model Instances To Dictionaries

I just searched for a method to convert a model instance to a dictionary in Django and the top few results were a bunch of custom methods in Django Snippets and Stack Overflow.  I was about to use one of those when I clicked on one last link that showed me a better solution.  There is a method already built into Django that does exactly what I want: django.forms.models.model_to_dict.

As I pointed that out to a coworker, he showed me that that’s basically the same output as the .values() method in the queryset api.  If you don’t specify a value to retrieve, it will retrieve the whole model instance as a dictionary.

Here’s the output of these two pieces of code:

>>> Q.objects.filter(id=6).values()
[{'short': u'oui', 'deleted': False, 'language_id': 3L, 'long': u'oui', 'place_holder': u'oui', 'id': 6L, 'question_id': 8L}]
>>> model_to_dict(Q.objects.filter(id=6)[0])
{'short': u'oui', 'language': 3L, 'deleted': False, 'question': 8L, 'long': u'oui', 'place_holder': u'oui'}

There are two differences here, and one of them is pretty important.  First, .values() turns a queryset into an iterable that yields dictionaries, and model_to_dict turns a model instance into a single dictionary.  As long as you know about it this is pretty trivial to overcome.  Second, .values() converts foreign keys to {‘<field_name>_id’: #} and model_to_dict converts them to {‘<field_name>’: #}.  Since my purpose in using this was to populate a form I had to convert the id’s into model instances and update the dictionary.  Not a big problem, but a bigger annoyance to solve than the first difference.