Tag Archives: django

Minimal Django script setup

import os, sys, pathlib # if script is in on 1 level deep # sys.path.append(str(pathlib.Path(__file__).parents[1].absolute())) sys.path.append(str(pathlib.Path(__file__).absolute())) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main.settings") import django django.setup() # import your django models # do your django work

Django Rest Framework QuerySet

I have just created this python library so that you can query the remote api just like the Django queryset. It is particularly usefully when used in Django ListView with pagination. https://github.com/variable/django-rest-framework-queryset 

Make sure you are closing the DB connections after accessing Django ORM in your threads

I was writing a service which import various feeds and then post to another RESTful API, simple enough as below: from django.db import connections class Receiver(PolymorphicModel): … class Database(Receiver): name = models.CharField(max_length=255) def get_data_source(self): return connections[name] Then the feed model: class Feed(models.Model): receiver = models.ForeignKey(‘Receiver’) def get_data_source(self): return self.receiver.get_real_instance().get_data_source() Then run this feed in trivial… Read More »

django-rest-framework: api versioning

Django Rest Framework is a very solid api framework, but it doesn’t provide out-of-box versioning mechanism, here is my attempt to implement version specific APIs. The goal is to achieve something like http://localhost:8000/api/(resource)/ http://localhost:8000/api/v1/(resource)/ plus allowing clients to specify the version in request header (X-Version), here is how we did it. Structure in side the… Read More »

Django CMS Haystack 2.0 Search Index

Currently django-cms-search doesn’t support haystack 2.0 yet, so here is my modified version to work on haystack 2.0 based on import datetime from haystack import indexes from cms.models.managers import PageManager from cms.models.pagemodel import Page from cms.models.pluginmodel import CMSPlugin class PageIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=False) pub_date = indexes.DateTimeField(model_attr=’publication_date’, null=True) login_required = indexes.BooleanField(model_attr=’login_required’) url = indexes.CharField(model_attr=’get_absolute_url’)… Read More »

Django admin UnicodeEncodeError

Don’t we all get confused by unicode encoding sometimes? Especially you wouldn’t expect this kind of error to happen in django admin. The problem is actually not in the admin section, the culprit is __unicode__ method in your model. when you have a unicode function like this: def __unicode__(self): return “{0}”.format(self.field_one) It is actually returning… Read More »