Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
How to deploy Django project to Heroku using Docker
In this Django Heroku guide, I will talk about how to deploy Django project to Heroku using Docker. -
Profiling & Optimizing Bottlenecks In Django
In the previous article, we have learnt where to start with performance optimization in django application and find out which APIs to optimize first. In this article, we will learn how to optimize those selected APIs from the application. Profling APIs With django-silk django-silk provides silk_profile function which can be used to profile selected view or a snippet of code. Let's take a slow view to profile and see the results. from silk.profiling.profiler import silk_profile @silk_profile() def slow_api(request): time.sleep(2) return JsonResponse({'data': 'slow_response'}) We need to add relevant silk settings to django settings so that required profile data files are generated and stored in specified locations. SILKY_PYTHON_PROFILER = True SILKY_PYTHON_PROFILER_BINARY = True SILKY_PYTHON_PROFILER_RESULT_PATH = '/tmp/' Once the above view is loaded, we can see the profile information in silk profiling page. In profile page, silk shows a profile graph and highlights the path where more time is taken. It also shows cprofile stats in the same page. This profile data file can be downloaded and used with other visualization tools like snakeviz. By looking at the above data, we can see most of the time is spent is time.sleep in our view. Profling APIs With django-extensions If you don't want to … -
Profiling & Optimizing Bottlenecks In Django
In the previous article, we have learnt where to start with performance optimization in django application and find out which APIs to optimize first. In this article, we will learn how to optimize those selected APIs from the application. Profling APIs With django-silk django-silk provides silk_profile function which can be used to profile selected view or a snippet of code. Let's take a slow view to profile and see the results. from silk.profiling.profiler import silk_profile @silk_profile() def slow_api(request): time.sleep(2) return JsonResponse({'data': 'slow_response'}) We need to add relevant silk settings to django settings so that required profile data files are generated and stored in specified locations. SILKY_PYTHON_PROFILER = True SILKY_PYTHON_PROFILER_BINARY = True SILKY_PYTHON_PROFILER_RESULT_PATH = '/tmp/' Once the above view is loaded, we can see the profile information in silk profiling page. In profile page, silk shows a profile graph and highlights the path where more time is taken. It also shows cprofile stats in the same page. This profile data file can be downloaded and used with other visualization tools like snakeviz. By looking at the above data, we can see most of the time is spent is time.sleep in our view. Profling APIs With django-extensions If you don't want to … -
Testing WizardView in Django
Sometimes, you just have to resort to a multi-step view to simplify data entry for a user. [Django](https://www.djangoproject.com) had an "included" package for this: `django.contrib.formtools`, until some years ago, when it moved into [it's own repository](https://django-formtools.readthedocs.io/en/latest/index.html). It's still very useful though, although there is a bit of a learning curve. I have some multi-step wizard views, for things where there are a bunch of different (sometimes dependent, but not necessarily) things we need to get from the user, and commit in an all-or-nothing way. Writing tests for these views is quite cumbersome, but I've recently come up with a couple of things that can make this less painful. The reason it's somewhat difficult is that the wizard, and the current step form both have form data, so to ensure there are no clashes between name fields, the forms are all prefixed. However, prefixes on forms mean that the data you need to pass to the form must also be prefixed in the correct way. {% highlight python %} class TestWizard(TestCase): def test_wizard_view(self): # user has been created... self.client.force_login(user) # url is the url for this wizard view. response = self.client.get(url) self.assertEqual(200, response.status_code) response = self.client.post(url, { 'wizard-current_step': 'first', 'first-field_a': 'value', … -
From Django 0.9 to Present - Russell Keith-Magee
PyCon Australia 2015: Money, Money, Money - Writing software, in a rich (wo)man’s world BeeWare Django 2008 Keynote Keynote: Why I Hate Django by Cal Henderson PyCon Australia 2017 - Red User, Blue User, MyUser, auth.User by Russell Keith-Magee django-improved-user PyCon 2019 Keynote Django for Beginners book DjangoX Starter Project PyCon Australia 2019 - Just Add Await: Retrofitting Async Into Django by Andrew Godwin SHAMELESS PLUGS William's books on Django Carlton's website Noumenal -
Revisions
Mistakes happen, and that’s part of a learning process. In a large project like Django, it can be hard to spot a mistake. Thanks to it being open source, anyone can see the code and fix the mistakes they see. In this post, I’ll explain how I found a vulnerability in contrib.postgres.fields.JSONField that allowed SQL injections to be performed. If you’re familiar with Python’s DB-API, you may have used the . -
Build a Python Jupyter Notebook Server with Docker & Heroku
Jupyter notebooks have become ... -
Джанго в роли микрофреймворка
Известно мнение, что Джанго не подходит для написания "наколеночных" проектиков, которым не нужно ничего особенно, кроме вывода HTML'а. Создание скелета проекта на Джанго считается работой, достаточно существенной для того, чтобы не заниматься ею ради пары функций. Мне всегда было "очевидно", что это не так, но недавно по оброненной коллегой фразе я понял, что это не значит, что это очевидно всем. Многие просто не задумываются об этом. Ну, вы знаете, как это бывает… Поэтому я хочу продемонстрировать создание Джанго-проекта минимальными усилиями. Упрощение Нужно отказаться от команды startproject. Она создаёт хороший скелет проекта с аннотированным файлом настроек, но если вы Джанго-проект видите не впервые, этим можно пренебречь. Файл manage.py — тоже не нужен, это просто локальный хелпер для django-admin.py Не нужно думать о проекте, как о контейнере для приложений, а следовательно не нужно оформлять свой код, как подключаемое приложение. Приложения — одна из самых сильных архитектурных черт Джанго, но для мелких задач эта гибкость никогда не понадобится. В итоге мы имеем что-то такое: settings.py: DEBUG = True ROOT_URLCONF = 'urls' TEMPLATE_DIRS = ['.'] urls.py: from django.conf.urls.defaults import * import views urlpatterns = patterns('', (r'^$', views.index), (r'^test/(\d+)/$', views.test), ) views.py: from django.shortcuts import render def index(request): return render(request, 'index.html', {}) def test(request, id): … -
MySQL and Security - Adam Johnson
Adam Johnson personal site django-mysql MariaDB Django Hosting Options Django’s Test Case Classes and a Three Times Speed-Up DjangoCon 2019 Europe - Django and Web Security Headers SHAMELESS PLUGS William's books on Django Carlton's website Noumenal -
Django Tutorial - ManyToManyField via a Comma Separated String in Admin & Forms
The `ManyToManyField` is super... -
My Appearance on DjangoChat
A few weeks ago I had the pleasure of talking over the internet with Will Vincent and Carlton Gibson about lots of Django-related topics. They somewhat informed me it was being recorded for a podcast. Now the day I anticipated and feared is here. I discovered through this tweet that my voice is online: Episode 27 - MySQL & Security with Adam Johnson (@AdamChainz) is now live! Adam is a Django core developer responsible for the popular django-mysql package. We discuss why MySQL still makes sense with Django, security, hosting on AWS, and more. https://djangochat.com We talked about all kinds of things including: How I got started with Django Why MySQL and MariaDB are still a competitive databases for Django apps—despite their relative unpopularity in the community and ecosystem fragmentation. Ways to host Django My security talk at DjangoCon Europe this year Testing Django applications, coverage and speeding up tests If you’re interested in Django, head on over to the website and listen to Episode 027: MySQL & Security. Enjoy! —Adam (P.S. Don’t get mixed up and go to the wrong Twitter account, @DjangoChat, unless you want to see an adorable French cat.) -
DjangoCon, Here We Come!
We’re looking forward to the international gathering at DjangoCon 2019, in San Diego, CA. The six-day conference, from September 22 - 27, is focused on the Django web framework, and we’re proud to attend as sponsors for the tenth year! We’re also hosting the second annual Caktus Mini Golf event. ⛳ If you’re attending DjangoCon, come play a round of mini golf with us. Look for our insert in your conference tote bag. It includes a free pass to Tiki Town Adventure Golf on Wednesday, September 25, at 7:00 p.m. (please RSVP online). The first round of golf is on us! And whoever shoots the lowest score will win a $100 Amazon gift card.* Talk(s) of the Town Among this year’s talented speakers is one of our own, Erin Mullaney (pictured). Erin has been with Caktus since 2015, and has worked as a contractor for us since July 2017. On Monday, September 23, she’ll share her experiences going from a full-time developer to a contractor in her talk, “Roll Your Own Tech Job: Starting a Business or Side Hustle from Scratch.” The talk will cover her first two years as a consultant, including how she legally set up her business … -
DjangoCon, Here We Come!
We’re looking forward to the international gathering at DjangoCon 2019, in San Diego, CA. The six-day conference, from September 22 - 27, is focused on the Django web framework, and we’re proud to attend as sponsors for the tenth year! We’re also hosting the second annual Caktus Mini Golf event. ⛳ If you’re attending DjangoCon, come play a round of mini golf with us. Look for our insert in your conference tote bag. It includes a free pass to Tiki Town Adventure Golf on Wednesday, September 25, at 7:00 p.m. (please RSVP online). The first round of golf is on us! And whoever shoots the lowest score will win a $100 Amazon gift card.* Talk(s) of the Town Among this year’s talented speakers is one of our own, Erin Mullaney (pictured). Erin has been with Caktus since 2015, and has worked as a contractor for us since July 2017. On Monday, September 23, she’ll share her experiences going from a full-time developer to a contractor in her talk, “Roll Your Own Tech Job: Starting a Business or Side Hustle from Scratch.” The talk will cover her first two years as a consultant, including how she legally set up her business … -
Python Tutorial - Google Geocoding API
In this short tutorial, we're ... -
Django Foreign Keys: Limiting Choices in Forms
I'm going to assume you're not... -
Heroku vs AWS Which is Best for Your Django project
In this Django Heroku tutorial, I will talk about the relationship and difference between Heroku and AWS. -
Django x Docker to Production on Heroku
Manually deploying a [project ... -
SEO friendly urls in Django
Examples sites built with Django usually use primary keys as the URL identifier for a resource. While this is the simplest and cleanest approach to resource urls, it's not optimized for SEO. It's [debatable](https://webmasters.stackexchange.com/questions/47342/are-keywords-in-urls-good-seo-or-needlessly-redundant) on whether or not keywords in urls matter for Google, but it's obvious that most of the major players have adopted this technique. Below are five examples of popular sites that all use keywords in urls to improve their SEO. - Stackoverflow - [https://stackoverflow.com/questions/8318911/why-does-html-think-chucknorris-is-a-color](https://stackoverflow.com/questions/8318911/why-does-html-think-chucknorris-is-a-color) - Wikipedia - [https://en.wikipedia.org/wiki/Python_(programming_language)](https://en.wikipedia.org/wiki/Python_(programming_language)) - Amazon.com - [https://www.amazon.com/Django-Unchained-Jamie-Foxx/dp/B00BJS7104/](https://www.amazon.com/Django-Unchained-Jamie-Foxx/dp/B00BJS7104/) - Reddit - [https://www.reddit.com/r/soccer/comments/c22vuf/referee_trolls_player/](https://www.reddit.com/r/soccer/comments/c22vuf/referee_trolls_player/) - Dev.to - [https://dev.to/danihodovic/optimizing-postgres-full-text-search-with-django-42hg](https://dev.to/danihodovic/optimizing-postgres-full-text-search-with-django-42hg) If you poke around at the top 100 sites as ranked by [Alexa](https://www.alexa.com/topsites) you will notice that most sites with public facing content use some sort of keywords approach in their urls. Besides being a possible SEO optimization strategy it also improves the chances that a user will click on [your link over other links.](https://stackoverflow.com/a/910741/2966951). Both Chrome and Firefox will match and highlight parts of urls that match the keywords if the user has visited the site previously. ![Google search bar](https://i.imgur.com/DxhpTeR.png) ## Show me the code Django doesn't have views that use keywords in urls out of the box, but it's trivial to add. I'll go … -
Key, index, and path transforms
It’s time for one of the most exciting important parts: transforms! This is probably one of the last few posts on this blog (at least for this year), since GSoC 2019 is almost finished and I’m wrapping up my project soon. In this post, I’ll explain how I implemented key, index, and path transforms to allow querying with JSON values. Actually, they aren’t made into different transforms, but a transform (called KeyTransform) that can be chained to form a JSON path. -
Multiple Category Classification with Keras, Tensorflow, Pandas, Numpy, & Python
In this one, we'll be creating... -
Adding charts to Django admin
## Introduction Django offers a functional admin UI out of the box with CRUD interface for db management. This covers most use cases for basic content and user management systems. However, it doesn't have exploratory views that show summaries or historical trends which is something you'd expect from an admin dashboard. Luckily, the django admin app is extensible and with a few tweaks we can add interactive Javascript charts to the admin. ## Problem I wanted to get a graph overview of the email subscribers over time on [findwork.dev](https://findwork.dev). Is the site growing or stagnating in terms of email subscribers? How many subscribers did we have last month? What week did we gain most subscribers? Are all subscribers verifying their emails? Using exploratory charts we can get a historical overview to how our site is performing. I initially explored the land of ready-made Django admin apps and dashboards. The requirements were that it included charting abilities, was well documented and looked good. While all of the apps I experimented with looked better that the default admin in terms of styling, they were either lacking in documentation or were unmaintained. - [xadmin](https://github.com/sshwsfc/xadmin) - no documentation in English - [django-jet](https://github.com/geex-arts/django-jet) - unmaintained … -
This Is How We Promote a Strong Culture With Distributed Teams
It’s no secret that building and maintaining a robust company culture is challenging for any organization. Is it any more difficult for distributed agile teams, in which an engineering organization is spread across multiple offices — or even across different countries and time zones? I’m Distillery’s General Manager. I’ve been with the company since 2012. As a fast-growing company with 150+ people distributed across 5 offices, 2 countries, and time zones 10 hours apart, I’ve got a strong perspective on this question.  What’s my answer? It’s not more difficult. It’s just different in certain ways. The bottom line is that there’s no “easy” way to build a strong company culture, whether your team is in one office or one hundred. Since it’s a consequence of how a company actually functions, it can’t be manufactured. It’s something you need to pay deliberate, daily attention to.  You can’t manufacture culture, but you can bring it to the surface. You can work to define it, demonstrate it, and protect it. By making our workplace culture a central focus for our people, we create a conversation and working environment that strengthens that culture. Here’s how we do it at Distillery.  Defining Our Company’s Culture  … -
How to Add Database Modifications Beyond Migrations to Your Django Project
On several Django projects I’ve worked on, there has been a requirement for performing database modifications beyond Django migrations. For example: Managing stored procedures Managing check constraints, which weren’t supported before Django 2.2 Importing static data from a file Recording migration operations in a log Let’s look at three approaches to extending Django to do this as neatly as possible. 1. Use Django migrations Often I find developers have only been taught how to use Django migrations for model operations. They might know some SQL, but since they haven’t used it within Django, they assume migrations can’t use SQL directly. They can! Many of the uses of custom migration-style SQL code that I’ve seen could be better implemented within migrations. Let’s take a look at an example we’ll use for the rest of the article. Imagine you’re running a Django version before 2.2 that doesn’t support database check constraints. You might add one to a database table with this SQL: ALTER TABLE myapp_book ADD CONSTRAINT percent_lovers_haters_sum CHECK ( (percent_lovers + percent_haters) = 100 ); This constraint will make the database raise an error for any rows added or updated in the myapp_book table that have a percentage of lovers and … -
API Calls within a Pandas Dataframe API using Pandas Apply
Whenever you're doing data ana... -
Feature-Policy updates - now required for an A+ on SecurityHeaders.com
In my blog post and DjangoCon Europe talk earlier this year How to Score A+ for Security Headers on Your Django Website, I covered that Feature-Policy was a “bonus header”. In a recent update, Scott Helme wrote that an A+ on SecurityHeaders.com now requires Feature-Policy. Also it no longer requires X-Xss-Protection (though it’s still a good idea). Chrome also has some Feature-Policy support enabled by default, so most users will be protected when it’s set. Previously it was hidden behind the “experimental web features” flag, but this is now only used for enabling Feature-Policy support for certain features. Opening the JavaScript console and querying for the list of features on Chrome 75 without the experimental flag on, I see 18 features allowed: > document.featurePolicy.allowedFeatures() < [ "accelerometer", "ambient-light-sensor", "autoplay", "camera", "encrypted-media", "focus-without-user-activation", "fullscreen", "geolocation", "gyroscope", "magnetometer", "microphone", "midi", "payment", "picture-in-picture", "speaker", "sync-xhr", "usb", "vr", ] I added some updates to my how-to on these changes. If you haven’t set the header previously, consider adding it for that sweet A+ score! You can add it on your Django apps with my django-feature-policy package. I updated django-feature-policy this morning to version 3.0.0 to include the latest set of features. Since I don’t …