All articles, tagged with “gotcha”

Django Forms Gotcha

Well, I just wasted 4 good hours of my time thinking I was facing a bug. I set the prefix for a form while trying to set the initial value for for a field. Only the first instance of the instantiated form would include the initial value. This code illustrates my problem:

    from django import forms

    class MyForm(forms.Form):
        names = forms.CharField(required=False)
        id = forms.CharField(widget=forms.HiddenInput,required=False)


    print [MyForm({'id':y},prefix=y).as_p() for y in range(2)]

    #output:
    #
    #[u'<p><label for="id_names">Names:</label> <input type="text" name="names" #id="id_names" /><input type="hidden" name="id" value="0" id="id_id" /></p>',
    # u'<p><label for="id_1-names">Names:</label> <input type="text" name="1-names" #id="id_1-names" /><input type="hidden" name="1-id" id="id_1-id" /></p>']
    #
    # Notice how 2nd form instance doesnt have value=1 for hidden input field.

Solution was simple. Thanks to the guys at #django on freenode, all I needed to do was instantiate my form as such:

MyForm(initial={'id':y})

That fixed it for me. I was told that when using data=, I need to match the data key to field name including the prefix. With initial keyword, you dynamically set that.

Django Evolution Gotcha

Django evolution is the closest thing to a steroid when it comes to enhancing the productivity of a Django developer working with RDBMSs. So close, it’s even got some nasty side effects if you rely on it so much.

I made the mistake of doing ./manage.py reset app after changing a model structure for an app that was being tracked by django-evolution. Almost all ./manage.py commands gave nasty errors whenever I try to use them afterwords. So I removed the django-evolution app from my installed app list, and got things working again.

Two days pass, and I fall into withdrawal from relying on this drug known as django evolution, I had to have it again. I installed it again after doing a ./manage.py flush, and db related management commands refused to work. Then it hit me. All I had to do was:

./manage.py reset django_evolution

Things then got back to normal. I believe what happened is django evolution got out of sync with my db state after the reset that I did. This solution surely fixed it, but I lost all the evolution history of my database. If anyone out there knows a better way to fix this problem, and still maintain previous history, I would be thankful.