Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Ports and Adapters in python - part two
Last time I wrote about how to do simple port & adapter in python. In this post, I will show to actually use them. I briefly remind you what is purpose of application build in this series: user will log in, then search with keyword so he can save any search result to database for read it later. I decided to first implement search mechanism for Reddit. This is what I will write today. Search request will be sent via GET. First, I need some form to handle this: 1 from django import forms 2 from django.conf import settings 3 4 from external_api.external_api_port import instantiated_port 5 6 class RedditSearchForm(forms.Form): 7 query = forms.CharField(label='search query', max_length=100) 8 9 def perform_search(self): 10 search_result = instantiated_port.search(self.cleaned_data['query']) 11 return search_result I defined simple form that has only one field: query which is CharField field with label. My form has one method perform_search. In this method, I import instantiated reddit port that takes instance of reddit adapter with settings from django settings module. Idealy this adapter should be singleton class. This is how it looks in reddit_adapter: from django.conf import settings # reddit adapter class here ... instantiated_adapter = RedditAdapter( settings.REDDIT_CLIENT_ID, settings.REDDIT_CLIENT_SECRET, settings.REDDIT_USERNAME, settings.REDDIT_PASSWORD ) … -
Ports and Adapters in python - part two
Last time I wrote about how to do simple port & adapter in python. In this post, I will show to actually use them. I briefly remind you what is purpose of application build in this series: user will log in, then search with keyword so he can save any search result to database for read it later. I decided to first implement search mechanism for Reddit. This is what I will write today. Search request will be sent via GET. First, I need some form to handle this: 1 from django import forms 2 from django.conf import settings 3 4 from external_api.external_api_port import instantiated_port 5 6 class RedditSearchForm(forms.Form): 7 query = forms.CharField(label='search query', max_length=100) 8 9 def perform_search(self): 10 search_result = instantiated_port.search(self.cleaned_data['query']) 11 return search_result I defined simple form that has only one field: query which is CharField field with label. My form has one method perform_search. In this method, I import instantiated reddit port that takes instance of reddit adapter with settings from django settings module. Idealy this adapter should be singleton class. This is how it looks in reddit_adapter: from django.conf import settings # reddit adapter class here ... instantiated_adapter = RedditAdapter( settings.REDDIT_CLIENT_ID, settings.REDDIT_CLIENT_SECRET, settings.REDDIT_USERNAME, settings.REDDIT_PASSWORD ) … -
Speed Comparison: Putting Pyston and PyPy to the Test
The most famous quote to characterize python speed is: It is fast enough I have used this quote many times, and I still believe that it applies to most circumstances if you throw enough hardware at the problem. Despite Python being “fast enough” for most applications, a few projects are working on making it even faster. The most well known is PyPy. It has been under active development for nearly a decade and is a production-ready implementation of the CPython API. In the last couple years, a competing project named Pyston has been seeing regular development and improvements. They're backed by Dropbox who has every reason to prioritize speed (considering that they manage massive amounts of code). They've also employed Guido van Rossum, the creator of Python, since 2012. Both Pyston and PyPy promise to deliver a faster Python Virtual Machine. They are doing so by applying a technique that has proven to be extremely efficient in JavaScript-land. This method is called "Just In Time compilation." Here's what the Pyston team team writes to explain their initiative: There are already a number of Python implementations using JIT techniques, often in sophisticated ways. PyPy has achieved impressive performance with its tracing … -
Evennia in pictures
Evennia in picturesby Griatch, September 2015This article was originally written for Optional Realities. Since it is no longer available to read on OR, I'm reposting it in full here. The MU* development system Evennia works quite differently from many traditional MU* code bases/servers and we get questions about this from time to time. This article will try to give an overview for outsiders - using pictures! Figure 1: The parts of the Evennia library Evennia is a game development library. What you see in Figure 1 is the part you download from us. This will not run on its own, we will soon initialize the missing “jigsaw puzzle” piece on the left. But first let’s look at what we’ve got. Looking at Figure 1 you will notice that Evennia internally has two components, the Portal and the Server. These will run as separate processes. The Portal tracks all connections to the outside world and understands Telnet protocols, websockets, SSH and so on. It knows nothing about the database or the game state. Data sent between the Portal and the Server is protocol-agnostic, meaning the Server sends/receives the same data regardless of how the user is connected. Hiding behind the Portal also … -
Send Email with SendGrid on Heroku for Django
A 2026 guide to sending transactional email from a Django app on Heroku with SendGrid: API-key auth (the literal apikey username), SMTP and django-anymail config from env vars, and the SPF/DKIM/DMARC domain authentication that keeps mail out of spam. -
Mastering Python
Mastering Python is finally out and available in your local book store. If you are an experienced Python developer, this might be the book for you. It will teach you the useful new features in Python 3 (currently up to 3.5) and show you a lot of Python tricks that you may not have seen before. As a Python developer with many years of experience I can guarantee you that you will learn something new. Quite a few sections result from original research which currently cannot (believe me, I’ve tried) be found online. Some of the more interesting subjects that are covered are asyncio and coroutines. Additionally, have you ever tried to apply the lambda calculus to Python? Give it a try, here’s the Quicksort algorithm using the Y combinator: >>> Y = lambda f: lambda *args: f(Y(f))(*args) >>> quicksort = Y(lambda f: ... lambda x: ( ... f([item for item in x if item < x&#91;0&#93;&#93;) ... + &#91;y for y in x if x&#91;0&#93; == y&#93; ... + f(&#91;item for item in x if item > x[0]]) ... ) if x else []) Link to this post! -
Code, Code, Code
I'm often asked by new programmers how they can forge a path into using their skills professionally. Or how they can get better at writing software. How to Improve Your Coding Skills This was my path. It may not be your path. This path also isn't in any particular order, all of them apply from the moment you start on the path. I coded. A lot. From silly little scripts to automating tasks to attempting full-blown projects. At work or for fun. I failed a lot, but learned along the way. I didn't jump from language to language. Instead I stayed in a few places for years and focused my learning on those tools. My 19+ year career can be summed up as FoxPro then Java then Python. In the middle of things I picked up JavaScript. Sure, I've dallied with a few things (Lisp, Haskell, Lua, Perl, ColdFusion, Go), but by staying focused on a small set of tools I'm better than mediocre. I coded lots. Yes, this is a repeat of #1. Once I got the basics of a language, I looked up best practices for each of them. Then I religiously adhered to them, even becoming dogmatic … -
Code, Code, Code
I'm often asked by new programmers how they can forge a path into using their skills professionally. Or how they can get better at writing software. How to Improve Your Coding Skills This was my path. It may not be your path. I coded. A lot. From silly little scripts to automating tasks to attempting full-blown projects. At work or for fun. I failed a lot, but learned along the way. I didn't jump from language to language. Instead I stayed in a few places for years and focused my learning on those tools. My 19+ year career can be summed up as FoxPro then Java then Python. In the middle of things I picked up JavaScript. Sure, I've dallied with a few things (Lisp, Haskell, Lua, Perl, ColdFusion, Go), but by staying focused on a small set of tools I'm better than mediocre. I coded lots. Yes, this is a repeat of #1. Once I got the basics of a language, I looked up best practices for each of them. Then I religiously adhered to them, even becoming dogmatic about it. In general this means my code is more easily read. More easily debugged. And most importantly, more easily … -
Code, Code, Code
I'm often asked by new programmers how they can forge a path into using their skills professionally. Or how they can get better at writing software. How to Improve Your Coding Skills This was my path. It may not be your path. This path also isn't in any particular order, all of them apply from the moment you start on the path. I coded. A lot. From silly little scripts to automating tasks to attempting full-blown projects. At work or for fun. I failed a lot, but learned along the way. I didn't jump from language to language. Instead I stayed in a few places for years and focused my learning on those tools. My 19+ year career can be summed up as FoxPro then Java then Python. In the middle of things I picked up JavaScript. Sure, I've dallied with a few things (Lisp, Haskell, Lua, Perl, ColdFusion, Go), but by staying focused on a small set of tools I'm better than mediocre. I coded lots. Yes, this is a repeat of #1. Once I got the basics of a language, I looked up best practices for each of them. Then I religiously adhered to them, even becoming dogmatic … -
Code, Code, Code
I'm often asked by new programmers how they can forge a path into using their skills professionally. Or how they can get better at writing software. How to Improve Your Coding Skills This was my path. It may not be your path. I coded. A lot. From silly little scripts to automating tasks to attempting full-blown projects. At work or for fun. I failed a lot, but learned along the way. I didn't jump from language to language. Instead I stayed in a few places for years and focused my learning on those tools. My 19+ year career can be summed up as FoxPro then Java then Python. In the middle of things I picked up JavaScript. Sure, I've dallied with a few things (Lisp, Haskell, Lua, Perl, ColdFusion, Go), but by staying focused on a small set of tools I'm better than mediocre. I coded lots. Yes, this is a repeat of #1. Once I got the basics of a language, I looked up best practices for each of them. Then I religiously adhered to them, even becoming dogmatic about it. In general this means my code is more easily read. More easily debugged. And most importantly, more easily … -
Querying Django Models with Q Objects
A practical guide to Django Q objects: combine conditions with OR, AND and NOT, mix Q with keyword filters, and build dynamic, multi-field search queries in Django 5. -
Django Aggregation: Count, Sum, Avg, Min, Max with aggregate() and annotate()
A practical, modern (Django 5.x) guide to aggregation in the Django ORM: when to use aggregate() vs annotate(), Count/Sum/Avg/Min/Max, grouping with values().annotate(), conditional aggregation, distinct counts, and how to avoid JOIN inflation. -
How to add CORS headers to a Django view for use with a Cordova app
Suppose you want to access some JSON data from a mobile app using Cordova. You have to bypass CORS restrictions in the web view, and to do that you have to provide some HTTP headers in your Django views. You can do this pretty easily by using this mixin in your Class Based Views: from django.http import HttpResponse class AllowCORSMixin(object): def add_access_control_headers(self, response): response["Access-Control-Allow-Origin"] = "*" response["Access-Control-Allow-Methods"] = "GET, OPTIONS" response["Access-Control-Max-Age"] = "1000" response["Access-Control-Allow-Headers"] = "X-Requested-With, Content-Type" def options(self, request, *args, **kwargs): response = HttpResponse() self.add_access_control_headers(response) return response Use it like in the example below. Here used together with Django Braces app: from django.views.generic import View from braces.views import AjaxResponseMixin, JSONResponseMixin class JsonView(JSONResponseMixin, AjaxResponseMixin, AllowCORSMixin, View): def get_ajax(self, request, *args, **kwargs): # ... get some data ... response = self.render_json_response({ 'data': data }) self.add_access_control_headers(response) return response -
Running Django on PyPy for Performance: Is It Worth It?
PyPy's JIT can make CPU-bound, pure-Python Django code several times faster, but most web apps are I/O-bound, so switching interpreters often buys little, while CPython 3.11+ has already closed much of the gap. An honest, benchmark-first 2026 guide to when PyPy is worth it for Django, the psycopg3 compatibility catch, and the query, cache, and async wins that usually beat it. -
Pretty Formatting JSON in the Django Admin
Recently I was writing code to interact with a third-party API. The API changes frequently, especially the data contained in responses. However, that data has to be saved and periodically needs to be audited. I wanted a data model flexible enough to handle these periodic changes without a lot of anguish, yet queryable. Since the API serves out queryable JSON, this made it a no-brainer for using django.contrib.postgres's JSONField. After a little bit of work, I had data samples to play with. Quickly my admin filled with chunks of JSON that looked something like this: {"field_12": 8, "field_16": 4, "field_6": 14, "field_7": 13, "field_18": 2, "field_2": 18, "field_4": 16, "field_15": 5, "field_9": 11, "field_3": 17, "field_8": 12, "field_11": 9, "field_17": 3, "field_10": 10, "field_0": 20, "field_1": 19, "field_13": 7, "field_5": 15, "field_14": 6} Kind of illegible, right? And that's a simple, flat example with just 20 keys. Imagine if this were a nested dictionary with 100 or 200 fields. For reference, that's the kind of data that I had that makes this kind of display nigh useless. So I cooked up this quick fix: import json from pygments import highlight from pygments.lexers import JsonLexer from pygments.formatters import HtmlFormatter from django.contrib … -
Pretty Formatting JSON in the Django Admin
Recently I was writing code to interact with a third-party API. The API changes frequently, especially the data contained in responses. However, that data has to be saved and periodically needs to be audited. I wanted a data model flexible enough to handle these periodic changes without a lot of anguish, yet queryable. Since the API serves out queryable JSON, this made it a no-brainer for using django.contrib.postgres's JSONField. After a little bit of work, I had data samples to play with. Quickly my admin filled with chunks of JSON that looked something like this: {"field_12": 8, "field_16": 4, "field_6": 14, "field_7": 13, "field_18": 2, "field_2": 18, "field_4": 16, "field_15": 5, "field_9": 11, "field_3": 17, "field_8": 12, "field_11": 9, "field_17": 3, "field_10": 10, "field_0": 20, "field_1": 19, "field_13": 7, "field_5": 15, "field_14": 6} Kind of illegible, right? And that's a simple, flat example with just 20 keys. Imagine if this were a nested dictionary with 100 or 200 fields. For reference, that's the kind of data that I had that makes this kind of display nigh useless. So I cooked up this quick fix: import json from pygments import highlight from pygments.lexers import JsonLexer from pygments.formatters import HtmlFormatter from django.contrib … -
Pretty Formatting JSON in the Django Admin
Recently I was writing code to interact with a third-party API. The API changes frequently, especially the data contained in responses. However, that data has to be saved and periodically needs to be audited. I wanted a data model flexible enough to handle these periodic changes without a lot of anguish, yet queryable. Since the API serves out queryable JSON, this made it a no-brainer for using django.contrib.postgres's JSONField. After a little bit of work, I had data samples to play with. Quickly my admin filled with chunks of JSON that looked something like this: {"field_12": 8, "field_16": 4, "field_6": 14, "field_7": 13, "field_18": 2, "field_2": 18, "field_4": 16, "field_15": 5, "field_9": 11, "field_3": 17, "field_8": 12, "field_11": 9, "field_17": 3, "field_10": 10, "field_0": 20, "field_1": 19, "field_13": 7, "field_5": 15, "field_14": 6} Kind of illegible, right? And that's a simple, flat example with just 20 keys. Imagine if this were a nested dictionary with 100 or 200 fields. For reference, that's the kind of data that I had that makes this kind of display nigh useless. So I cooked up this quick fix: import json from pygments import highlight from pygments.lexers import JsonLexer from pygments.formatters import HtmlFormatter from django.contrib … -
Where to Find Cakti at PyCon 2016
As Django developers, we always look forward to PyCon. This year, working with the Python Software Foundation on the design for PyCon 2016’s site kindled our enthusiasm early. Our team is so excited for all the fun to begin. With an array of fantastic events, speakers, and workshops, we thought we would highlight all the events we’ll be participating in. Come find us! -
So you want a new admin?
Django’s admin site is about 12 years old. It started circa early 2004 as an internal CMS at the Lawrence Journal-World, was released as part of Django in 2005, and has been chugging away ever since. There’s been some substantial re-writes along the way – magic-removal, new forms, the flat theme – but for the most part the admin’s stayed pretty much the same for that entire time. The interface, functionality, and CRUD-oriented workflow haven’t really changed since those early years at the Journal-World. -
Working with Django Plugins
Django-plugins is a package that helps you to build apps more reusable. It is currently tested with Python 2.7, 3.2, 3.3, and 3.4 along with Django versions 1.7 and 1.8. It might well work with other versions. By using 'Django-plugins', you can define, access plugins and plugin points. Installation: $ pip install django-plugins * Plugins are stored as python objects and synchronized to database called plugin models(PluginPoint, Plugin). * Both Plugin and plugin models has a name and title attributes. And each plugin point/plugin can be marked as enabled/disabled/removed using 'status' field in respective models from Django admin panel. * Plugins are the classes which are hardcoded, which means they cannot be modified directly by the users. But they can change the database objects of those plugins. In this way, you can provide the flexibility to the user to change plugins. NOTE: You should always use plugin attributes (name, title) from model objects but not from plugins. * All defined plugins and plugin points are synchronized to database tables using Django management command 'sync plugins' or 'sync DB'. 'sync plugins' command detects the removed plugin points, plugins and marks them as 'REMOVED' in the database. Features of 'Django-plugins': Synchronization with … -
Using Sentry To Track Django live Events
In the previous tutorial you saw how to setup sentry, let us now learn how to track exceptions and events in SENTRY. We will setup client and server end tracking for Django Project. Note: My domain is set as "http://sentry.domain.com". Now after first login the screen should be similar to this. As per Sentry's Internal Architecture, Team will have access to projects. Create a team and assign a project to team, every member in team will now have access to it. As per your convineance. any combination of members can grouped as teams (which can be managed in Team Settings option in Dashboard page). Creating Team and Project. Click on Create Team button in Dashboard. decide a Team Name and save changes create a Project. In Project DashBoard> Settings > Client Keys, you can find DSN (reffered in this tutorial as dsn) and DSN (Public) - (Reffered in this tutorial as public-dsn) Modifications for Django Application. The recieving end is sentry but error tracker and logger is RAVEN, Install raven in Django Project environment pip install raven open settings.py include the below lines in settings.py RAVEN_CONFIG = { 'dsn': '<your-dsn-here>', } LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'root': { 'level': 'WARNING', 'handlers': ['sentry'], }, 'formatters': { 'verbose': { … -
Debugging Django Management Commands in PyCharm
Photo by Jill Heyer My favorite editor for Python projects is PyCharm. Besides editing code, it allows you to inspect the database, work with Git repositories, run management commands, execute bash commands and Python scripts, and debug code just in the same window. In this article, I will show you how to set breakpoints and debug Django management commands visually in PyCharm. Django management commands are scripts that can be executed on your Django project to do something with the project database, media files, or code. Django itself comes with a bunch of commands like: migrate, runserver, collectstatic, makemessages, and clearsessions. Management commands can be executed like this: (myproject_env)$ python manage.py clearsessions If you want to create a custom management command in your project, you can find how to do that in the official Django documentation. Also you can find some practical examples in the Chapter 9, Data Import and Export of the Web Development with Django Cookbook - Second Edition. In this example, I won't create any new management command, but will debug the clearsessions command that is coming from Django and is located at django/contrib/sessions/management/commands/clearsessions.py. First of all, let's click on "Edit Configurations..." in the top toolbar just … -
Django meetup Amsterdam 18 May 2016
Summary of the Django meetup organized at crunchr in Amsterdam, the Netherlands. (I gave a talk on the django admin, which I of course don't have a summary of, yet, though my brother made a summary of an almost-identical talk I did the friday before) Reducing boilerplate with class-based views - Priy Werry A view can be more than just a function. They can also be class based, django has quite a lot of them. For example the TemplateView that is very quick for rendering a template. Boilerplate reduction. Django REST framework is a good example of class based views usage. It really helps you to reduce the number of boring boilerplate and concentrate on your actual code. Examples of possible boilerplate code: Parameter validation. Pagination. Ordering. Serialisation. They wanted to handle this a bit like django's middleware mechanism, but then view-specific. So they wrote a base class that performed most of the boilerplate steps. So the actual views could be fairly simple. It also helps with unit testing: normally you'd have to test all the corner cases in all your views, now you only have to test your base class for that. Custom base classes also often means you … -
Evennia 0.6 !
As of today, I merged the development branch to make version 0.6 of the MU* development system and server Evennia. Evennia 0.6 comes with a lot of updates, mainly in the way Evennia talks to the outside world. All communication is now standardized, so there are no particular treatment of things like text - text is just one of any standardized commands being passed between the server the client (whether over telnet, ssh, websockets or ajax/comet). For example the user can now easily plug in "inputfuncs" to handle any data coming from the client. If you want your client to offer some particular functionality, you just need to plop in a python function to handle it, server-side. We also now offer a lot of utility functions for things like monitoring change (tell the client whenever your health status changes so it can update a health bar or flash the screen).The HTML5 webclient has itself updated considerably. Most is happening behind the scenes though. Notably the webclient's javascript component is split into two: evennia.js, acts as a library for handling all communication with the server part of Evennia. It offers events for a gui library to plug into and send/receive. It will … -
Ports and Adapters in python - part one
First part of series about Django application made using Ports and Adapters design pattern.