'Python' Category

  • Auto trimming field value / Django forms

    June 7, 2010

    I don’t know why this is not done by default, but.. from django import forms class TrimmedCharField(forms.CharField): def clean(self, value): return forms.CharField.clean(self, value.strip()) class Form1(forms.Form): f1 = TrimmedCharField(widget=forms.Textarea(attrs={‘rows’: 6})) f2= TrimmedCharField(widget=forms.Textarea(attrs={‘rows’: 6}))

  • django add bitwise logics to the filter query

    April 9, 2010

    Django has a great ORM, but it has some limitations while performing queries, e.g. it does not allow to do bitwise operation. Likely, django’s QuerySet has extra method (http://docs.djangoproject.com/en/dev/ref/models/querysets/#extra-select-none-where-none-params-none-tables-none-order-by-none-select-params-none). This method allows developers to write raw sql that will be included into the generated by ORM query. The tricky part is that all fields included […]

  • check login decorator for json responses

    March 21, 2010

    Django has a login_required decorator that redirects to the login page if user is not authenticated, here I’ll show how to write a custom decorator for json responses. If the uses is authenticated then decorated function returns the desired data otherwise some error in json format. NB – this decorator is for view functions with […]

  • dynamic forms in dajngo

    March 18, 2010

    Django has a very convenient forms framework and I want to show how to implement a form with dynamic set of fields. First – declare a form class: from django import forms class SomeAddressForm(forms.Form): pass Then the tricky part – declare a function that returns type of dynamic form: def getAddressForm(addMoreField): fields = {“city” : […]

  • Have ascii coding error in django admin?

    March 10, 2010

    If you have some unicode data in tables e.g. some Russian names and want them to be displayed  by default you need to do some trick: class SomeTable(models.Model): name = models.CharField(max_length=def_max_length) def __unicode__(self): return “%s” % self.name See that – instead of returning self.name directly I returned “%s” % self.name and admin panel is shining!

  • SQLAlchemy smooth queries

    October 2, 2009

    Suppose we have a table A and a child table B and we need the following queries: Select all records from A where their Title like ‘something’; Select count of records in the result of the previous one; Select all records from A that have children in B and Title like “something”; Select all records […]

  • urllib and cookies

    September 10, 2009

    urllib doesn’t have cookie support and it’s difficult to test a django application that uses sessions as session id is stored in the cookies. However, urllib2 is able to handle cookies: import urllib2, cookielib jar = cookielib.CookieJar() handler = urllib2.HTTPCookieProcessor(jar) opener = urllib2.build_opener(handler) urllib2.install_opener(opener) data = urllib2.urlopen(someurl).read() Source: http://coding.derkeiler.com/Archive/Python/comp.lang.python/2006-04/msg04229.html

  • myLocation Symbian Client

    June 24, 2009

    Как и обещал, подробнее рассказываю про клиента для симбиана. Итак, проста до нельзя – на первом экране предлагается ввести настройки для подключения к серверу, на который будут отправляться координаты или же, если это уже не первый запуск, просто стартовать.

  • Django + new thread

    June 5, 2009

    Not long ago I needed to start a new thraed in a django application. After some googling I found an example: import threading from django.core.mail import send_mail def foo(request, identifier): data = get_some_data(identifier) try: error_check(data) # raise exception if data invalid except InvalidData, e: # Format our information here, in the main thread subject = […]

  • Reverse string Python

    May 28, 2009

    Вот вроде уже знаком с питоном неплохо, но он все не перестает меня удивлять – понадобилось тут обратить строчку, а метода такого нет у строки – ну не писать же цикл! И правда, не надо – достаточно воспользоваться расширением для получения среза: def reverse(str): return str[::-1] Очередной раз питон удивляет. Почитать подробнее

Powered by Wordpress and MySQL. Theme by Shlomi Noach, openark.org