Articles Tagged django

Trap in counting related objects in Django

Trap in counting related objects in Django

Task: for every object count number of related objects satisfying some conditions.

Example:

class Category(models.Model):
    title = models.CharField(max_length=50)

class Article(models.Model):
    title = models.CharField(max_length=50)
    category = models.ForeignKey(Category)
    approved_at = models.DateTimeField(blank=True, null=True)

Pay attention at field Article.approved_at, it contains article approval time and it can be null.

Create test data:

from django.utils import timezone

c1 = Category.objects.create(title='c1')
c2 = Category.objects ...

Posted on 2017-01-14

Django: signal or model method?

Django: signal or model method?

When I needed to implement some functionality on model saving, I always asked a question to myself - where to place it. In signal or in model method save()? Let's see, what and when is more applicable.

When use model methods save(), delete()?

To my mind class methods are more usable, if logic concerns exclusively current model. For example, fill some field on model saving according to data from other fields.

Some people say, that ...

Posted on 2016-08-01

Trying JSON in Django and PostgreSQL (and compare with MongoDB)

Trying JSON in Django and PostgreSQL

New JSONField will be added in Django 1.9, it can be used with PostgreSQL >= 9.4. Let's try to work with it and find out, in what situations it can be useful.

Currently django 1.9 alpha is available, final version is scheduled on December 2015. Alpha can be installed with pip:

pip install --pre django

Now imagine that we have an e-commerce site, where we offer products of different types. For example ...

Posted on 2015-09-30

OAuth and django rest framework

OAuth and django rest framework

This is a well known topic, but i can't find the existing solution that will fully satisfy me. So i write it by myself :).

Assume we have a "single page" web site, that is talking with backend via REST API. Client side can be written with ember, angularjs or some like this. Backend - django rest framework (DRF). We've got a task - add social login (OAuth protocol).

How it will look like in case ...

Posted on 2015-07-18

Debug SQL in django test

Debug SQL in django test

In django tests we can measure number of sql queries:

def test_home(self):
    with self.assertNumQueries(1):
        response = self.client.get('/')
    self.assertEqual(response.status_code, 200)

If code in context of assertNumQueries will make other number of DB attempts than expected (here 1), test will throw error. But when test fails it is sometimes hard to understand, what unexpected query was made. To debug such case very useful to log SQL expressions to console. Below ...

Posted on 2015-03-04

Django celery setup

Django celery setup

To enable celery in new django project i often look in previous ones to refresh in my memory some steps: what settings should be specified, how to launch, how to stop and so on.

Here i want to combine all together in one place.

What we must get as a result

  1. Add delayed task executing in django project, controlled by celery, to not load current django process. Examples of such tasks: email sending, working with ...

Posted on 2014-11-02

Nested SQL queries in Django

Nested SQL queries in Django

Did you know, that Django ORM can do nested SQL queries? Shame on me, but i've found it not so long ago.

So, lets say we have such models of Nursery and Pet:

class Nursery(models.Model):
    title = models.CharField(max_length=50)

class Pet(models.Model):
    name = models.CharField(max_length=50)
    nursery = models.ForeignKey(Nursery, related_name='pets')

We need to get all pets, that are placed in given nurseries. For example, in nurseries with ...

Posted on 2014-09-09

Send email in django project with mandrill service

Send email in django project with mandrill service

To send email messages from server we can just use SMTP protocol. But there is another way - special email services. I'll describe one of them here, mandrill.com.

Advantages

  • Detailed statistic of sent emails. How many were sent, to whom, when. How many were opened, what links were clicked.
  • Message templates. They can be modified through mandrill service, no need to create anything in django admin. It is possible to use variables in ...

Posted on 2014-03-18

Django project: from beginning to working server

In this post i'll describe my experience of deploying django project to VPS-hosting.

Steps of deploying and server setup:

  1. Creation of django project
  2. Deploy setup
  3. Server setup
  4. Deploy

Creation of django project

Assume, that project is called myproject.

First, create it on local machine. We'll need pip and virtualenv (if not installed yet).

Create virtual environment:

virtualenv venv-myproject

Acitvate it:

# on *nix system
source venv-myproject/bin/activate

REM on windows
venv\Scripts\activate ...

Posted on 2013-11-13

Django logging settings

Let's look at default django logging settings and try to make them more useful.

Here what we have in settings.py after command django-admin.py startproject project_name (django 1.5):

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how ...

Posted on 2013-09-26

Django queryset.count cache

Django queryset.count cache

Once i mentioned, that my django application makes several similiar queries like 'SELECT COUNT(*) ...'. As it turns out (for me it was surprise), queryset.count() has not obvious cache. But let me start the story from the beginning (and sorry for my english :) ).

As it is known, django's queryset is lazy and have cache.

Lets say we have such model:

class Item(models.Model):
    name = models.CharField(max_length=50)

When some django query is ...

Posted on 2013-07-11

Parse url which contains unicode query, using urlparse.parse_qs

Task: get dictionary of URL GET query. For example, we have following url:

http://example.com/?key=value&a=b

it is needed to get a dict:

{'key': ['value'], 'a': ['b']}

Values are lists, because one key may have several values:

In: http://example.com/?key=value&a=b&a=c
Out: {'key': ['value'], 'a': ['b', 'c']}

In python there is a function urlparse.parse_qs for that purpose:

>>> import urlparse
>>> query = "key=value&a=b ...

Posted on 2013-05-22

Django admin site optimisation

Django admin site optimisation

It is known, that less amount of database attempts leads to better performance. Usually admin page - part of site with low traffic, but anyway it is good, if no additional database calls happen there. It is more pleasant to use it, because page renders faster and also frees server resources.

In this post i'll try to reduce some database attempts in admin page, when model method __unicode__ contains related object field. I suppose, that ...

Posted on 2013-04-12

Multilanguage site on django without redirects

Starting from django 1.4, it is possible to set url prefix for each activated language. For example, we want site, that will have russian and english version.

To do it, add following to settings.py:

    # default language, it will be used, if django can't recognize user's language
    LANGUAGE_CODE = 'ru'

    # list of activated languages
    LANGUAGES = (
        ('ru', 'Russian'),
        ('en', 'English'),
    )

    # enable django’s translation system
    USE_I18N = True

    # specify path for translation files
    LOCALE_PATHS = (
        os ...

Posted on 2013-02-26

MobileESP: Easily detect mobile web site visitors

Script will be useful, if you want to show different version of site for desktop computers and mobile devices. Big variety of methods to detect mobile type. Avaliable in different languages, including python. The port to python was made by me with help from my freelance customer.

Here how it can be used in django project:

from mobileesp import mdetect

user_agent = request.META.get("HTTP_USER_AGENT")
http_accept = request.META.get("HTTP_ACCEPT")
if user_agent and http_accept:
    agent ...

Posted on 2012-11-29

Debug django project with embedded python debugger pdb

I use sublime-text as code editor. It doesn't have a debugger, so to debug django projects i often used

print var_name

and look for output in local development server console. I use this approach today also, but sometimes it is great to run code step by step to see variables at each step.

It can be done with embedded python debugger pdb:

import pdb; pdb.set_trace()

I.e. we put this line in needed ...

Posted on 2012-11-18

This site

Features:

Often reading other blogs i had a wish to start my own, but i just can't find time for it. Also i was wondering, what will i write ...

Posted on 2012-08-28