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 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 [...]
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 [...]
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» : [...]
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!
Допустим, что имеется таблица A и дочерняя таблица B и нам нужны следующие запросы : Все записи из А у которых поле Title like ‘something’; Число этих записей; Все записи из A, у которых есть дочерние записи в B и поле Title like «something»; Все записи из A, у которых нет дочерних записей в B [...]
urllib не имеет поддержку куки и протестировать джанго-приложение, использующее сессии затруднительно (идентификатор сессии хранится в куки). Но urllib2 поддерживает куки: import urllib2, cookielib jar = cookielib.CookieJar() handler = urllib2.HTTPCookieProcessor(jar) opener = urllib2.build_opener(handler) urllib2.install_opener(opener) data = urllib2.urlopen(someurl).read() Источник: http://coding.derkeiler.com/Archive/Python/comp.lang.python/2006-04/msg04229.html
Как и обещал, подробнее рассказываю про клиента для симбиана. Итак, проста до нельзя — на первом экране предлагается ввести настройки для подключения к серверу, на который будут отправляться координаты или же, если это уже не первый запуск, просто стартовать.
Понадобилось сделать что-то вроде запуска отдельного потока в джанго-приложении, работающем под апачем. В сети везде попадается один и тот же пример для такого случая: 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 [...]
Вот вроде уже знаком с питоном неплохо, но он все не перестает меня удивлять — понадобилось тут обратить строчку, а метода такого нет у строки — ну не писать же цикл! И правда, не надо — достаточно воспользоваться расширением для получения среза: def reverse(str): return str[::-1] Очередной раз питон удивляет. Почитать подробнее