Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Automatic Created and Updated DateTime Fields for Django Models
I'm leaving this to my future self, as I keep forgetting it over and over again. If you want to add "create" and "update" time logging to your model, it's as simple as: from django.db import models class Task(models.Model): created = models.DateTimeField(auto_now_add=True) updated ... Read now -
Django 2.0 support is here!
Long time no blog.. However, this one brings some good news! Most of our packages have been updated to support Django 2.0. They are easily to recognize, because all upgraded packages have been given a “2.0” version number. This choice simplifies the version management across all packages, and marks a clear support baseline. The 2.0 packages support Django 1.10, 1.11 and 2.0. If you still run on Django 1.8, you can use the 1.x series. There have been a few backports to ease the transition for old projects. Available are: .hll { background-color: #ffffcc } .code149-c { color: #408080; font-style: italic } /* Comment */ .code149-err { border: 1px solid #FF0000 } /* Error */ .code149-k { color: #008000; font-weight: bold } /* Keyword */ .code149-o { color: #666666 } /* Operator */ .code149-ch { color: #408080; font-style: italic } /* Comment.Hashbang */ .code149-cm { color: #408080; font-style: italic } /* Comment.Multiline */ .code149-cp { color: #BC7A00 } /* Comment.Preproc */ .code149-cpf { color: #408080; font-style: italic } /* Comment.PreprocFile */ .code149-c1 { color: #408080; font-style: italic } /* Comment.Single */ .code149-cs { color: #408080; font-style: italic } /* Comment.Special */ .code149-gd { color: #A00000 } /* Generic.Deleted */ .code149-ge … -
Handling CORS in Django REST Framework
If you are building applications with Django and modern front-end/JavaScript technologies such as Angular, React or Vue, chances are that you are using two development servers for the back-end server (running at the port 8000) and a development server (Webpack) for your front-end application. When sending HTTP requests from your front-end application, using the browser's fetch API, the Axios client or the jQuery $.ajax() method (a wrapper for the JavaScript XHR interface), to your back-end API built with Django REST framework the web browser will throw an error related to the Same Origin Policy. Cross Origin Resource Sharing or CORS allows client applications to interface with APIs hosted on different domains by enabling modern web browsers to bypass the Same origin Policy which is enforced by default. CORS enables you to add a set of headers that tell the web browser if it's allowed to send/receive requests from domains other than the one serving the page. You can enable CORS in Django REST framework by using a custom middleware or better yet using the django-cors-headers package Using a Custom Middleware First create a Django application: python manage.py startapp app Next you need to add a middleware file app/cors.py: class CorsMiddleware(object): … -
Handling CORS in Django REST Framework
If you are building applications with Django and modern front-end/JavaScript technologies such as Angular, React or Vue, chances are that you are using two development servers for the back-end server (running at the port 8000) and a development server (Webpack) for your front-end application. When sending HTTP requests from your front-end application, using the browser's fetch API, the Axios client or the jQuery $.ajax() method (a wrapper for the JavaScript XHR interface), to your back-end API built with Django REST framework the web browser will throw an error related to the Same Origin Policy. Cross Origin Resource Sharing or CORS allows client applications to interface with APIs hosted on different domains by enabling modern web browsers to bypass the Same origin Policy which is enforced by default. CORS enables you to add a set of headers that tell the web browser if it's allowed to send/receive requests from domains other than the one serving the page. You can enable CORS in Django REST framework by using a custom middleware or better yet using the django-cors-headers package Using a Custom Middleware First create a Django application: python manage.py startapp app Next you need to add a middleware file app/cors.py: class CorsMiddleware(object): … -
How python's import machinery works
Glossary Let's begin with the basics. From now on when we say the word python we mean python 3.6. Python 3 is the future and (who knows) python 4 will be the future of python 3 etc. Stop using python 2! I'll try to be concise and simple, although the documentation about modules and packages is pretty straight forward. Go ahead and take a look to either learn what these concepts are or just refresh your memory. Python module When we say python module or just module we mean a simple python file, i.e models.py or utils.py. A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. When you put a bunch of modules under a directory then this directory is called a python package. Python package When we say python package or simply just package we mean a directory that contains one or more modules. Packages are a way of structuring Python’s module namespace by using “dotted module names”. Of course, a package may contain a bunch of other directories (packages) which themselves may contain a bunch of other modules mixed with other packages etc. You get … -
Hola, PyCon Colombia!
We (me and Audrey) are going to be giving a keynote speech at PyCon Colombia on February 11th! Hooray! We'll be arriving in Medellin late evening on February 7th and staying a while longer after the conference so we can have the time to explore the lovely city of Medellin. We're very excited, because travel is a rarity for us now and Medellin (and the surrounding area) is supposed to be quite beautiful. Plus, all the Colombians we know online are excellent people - we can't wait to meet them! Our hope is that on the day after PyCon Colombia we can see the sights and eat the foods with Colombians who know Medellin. So let me know if you want to meet up! Hasta pronto! -
Hola, PyCon Colombia!
We (me and Audrey) are going to be giving a keynote speech at PyCon Colombia on February 11th! Hooray! We'll be arriving in Medellin late evening on February 7th and staying a while longer after the conference so we can have the time to explore the lovely city of Medellin. We're very excited, because travel is a rarity for us now and Medellin (and the surrounding area) is supposed to be quite beautiful. Plus, all the Colombians we know online are excellent people - we can't wait to meet them! Our hope is that on the day(s) after PyCon Colombia we can see the sights and eat the foods with Colombians who know Medellin. So let me know if you want to meet up! Hasta pronto! -
Adding JWT Authentication to Python and Django REST Framework Using Auth0
In this tutorial we'll learn how to add JWT authentication to an API built with Django REST framework. Basically we'll use the djangorestframework-jwt package for adding JWT authentication as you would normally do except that we'll change JWT_AUTH to use Auth0. This tutorial assumes you already have a development machine with Python 3 and pip installed and will cover the following points: We'll see how to create a virtual environment, install Django and the other dependencies (Django REST framework and djangorestframework-jwt) We'll see how to create an Auth0 API We'll see how to integrate Auth0 JWT authentication with Django We'll briefly talk about using Auth0 Rules for detecting signup We'll see how to add some Django views for testing JWT We'll see how to use Postman for testing JWT authentication with Auth0 Creating the Django Project So head over to your terminal then create a new virtual environment and activate it using the venv module in your current working directory: python3 -m venv ./myenv source myenv/bin/activate Next install Django using pip: pip install django Now you'll need to create a new Django project using: django-admin startproject auth0-django-example Next create a new application in your project cd auth0-django-example python manage.py startapp … -
QuickTip: Django and AngularJS Conflicting Interpolation Symbols
When using the Django framework with the AngularJS MVC framework for building modern single page applications or SPAs, one of the issues you will encouter is related to both frameworks using the same symbols for template tags i.e { { and } }. So in this quick tip post we'll see how to change the interpolation symbols in AngularJS to avoid these conflicts. Luckliy for us, AngularJS provides the $interpolateProvider provider which allows developers to customize the interpolation symbols which default to { { and } }. Used for configuring the interpolation markup. Defaults to . This feature is sometimes used to mix different markup languages, e.g. to wrap an AngularJS template within a Python Jinja template (or any other template language). Mixing templating languages is very dangerous. The embedding template language will not safely escape AngularJS expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS) security bugs! -- https://docs.angularjs.org/api/ng/provider/$interpolateProvider Simple AngularJS Example Let's see a simple example: Go ahead and create a base template ng-base.html file in your templates folder then add the following content { % load staticfiles % } <!DOCTYPE html> <html lang="en" ng-app='demoApp'> <head> <base href="/"> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> … -
Adding JWT Authentication to Python and Django REST Framework Using Auth0
In this tutorial we'll learn how to add JWT authentication to an API built with Django REST framework. Basically we'll use the djangorestframework-jwt package for adding JWT authentication as you would normally do except that we'll change JWT_AUTH to use Auth0. This tutorial assumes you already have a development machine with Python 3 and pip installed and will cover the following points: We'll see how to create a virtual environment, install Django and the other dependencies (Django REST framework and djangorestframework-jwt) We'll see how to create an Auth0 API We'll see how to integrate Auth0 JWT authentication with Django We'll briefdly talk about using Auth0 Rules for detecting signup We'll see how to add some Django views for testing JWT We'll see how to use Postman for testing JWT authentication with Auth0 Creating the Django Project So head over to your terminal then create a new virtual environment and activate it using the venv module in your current working directory: python3 -m venv ./myenv source myenv/bin/activate Next install Django using pip: pip install django Now you'll need to create a new Django project using: django-admin startproject auth0-django-example Next create a new application in your project cd auth0-django-example python manage.py startapp … -
QuickTip: Django and AngularJS Conflicting Interpolation Symbols
When using the Django framework with the AngularJS MVC framework for building modern single page applications or SPAs, one of the issues you will encouter is related to both frameworks using the same symbols for template tags i.e { { and } }. So in this quick tip post we'll see how to change the interpolation symbols in AngularJS to avoid these conflicts. Luckliy for us, AngularJS provides the $interpolateProvider provider which allows developers to customize the interpolation symbols which default to { { and } }. Used for configuring the interpolation markup. Defaults to . This feature is sometimes used to mix different markup languages, e.g. to wrap an AngularJS template within a Python Jinja template (or any other template language). Mixing templating languages is very dangerous. The embedding template language will not safely escape AngularJS expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS) security bugs! -- https://docs.angularjs.org/api/ng/provider/$interpolateProvider Simple AngularJS Example Let's see a simple example: Go ahead and create a base template ng-base.html file in your templates folder then add the following content { % load staticfiles % } <!DOCTYPE html> <html lang="en" ng-app='demoApp'> <head> <base href="/"> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> … -
How to Implement Multiple User Types with Django
This is a very common problem many developers face in the early stages of the development of a new project, and it’s also a question I get asked a lot. So, I thought about sharing my experience with previous Django projects on how to handle multiple user types. I’ve tried many different strategies. In this tutorial I will share my thoughts on this particular topic and share with you the strategies that worked best for me, depending on the requirements of the project. Many of the design decisions depends on the requirements and business model of the application you are developing. I will try to cover as many different scenarios as possible. Read carefully and pick the best option for you. If you learn better with examples or you are in a hurry right now, jump to the practical example. Otherwise, keep reading. Rules of Thumb What you are going to read next is not written in a stone. It’s just some general recommendations that fits most cases. If you have a good reason, or if not following those recommendations will result in a better application design, go ahead and break the “rules”! 1. No matter what strategy you pick, … -
Adding the Django CSRF Protection to React Forms
In this tutorial you'll see how you can handle the Django CSRF token in React when using the Axios client or the fetch API. We'll also see how you can add CSRF in forms rendered dynamically with React More often than not when you are building React/Redux apps with a Django framework you'll need to send POST, PUT, PATCH and DELETE requests (which require a valid CSRF token included in each request) against an API endpoint using an HTTP client library such as Axios or the browser standard fetch API. CSRF stands for Cross-Site Request Forgery and it's a type of Cross Site Scripting attack that can be sent from a malicious site through a visitor's browser to your server. Django has a built in protection against CSRF attacks using the CSRF middleware which's included by default with each new project. Here is what Django docs says about the CSRF middleware The CSRF middleware and template tag provides easy-to-use protection against Cross Site Request Forgeries. This type of attack occurs when a malicious website contains a link, a form button or some JavaScript that is intended to perform some action on your website, using the credentials of a logged-in user … -
Adding the Django CSRF Protection to React Forms
In this tutorial you'll see how you can handle the Django CSRF token in React when using the Axios client or the fetch API. We'll also see how you can add CSRF in forms rendered dynamically with React More often than not when you are building React/Redux apps with a Django framework you'll need to send POST, PUT, PATCH and DELETE requests (which require a valid CSRF token included in each request) against an API endpoint using an HTTP client library such as Axios or the browser standard fetch API. CSRF stands for Cross-Site Request Forgery and it's a type of Cross Site Scripting attack that can be sent from a malicious site through a visitor's browser to your server. Django has a built in protection against CSRF attacks using the CSRF middleware which's included by default with each new project. Here is what Django docs says about the CSRF middleware The CSRF middleware and template tag provides easy-to-use protection against Cross Site Request Forgeries. This type of attack occurs when a malicious website contains a link, a form button or some JavaScript that is intended to perform some action on your website, using the credentials of a logged-in user … -
Conditional aggregation in Django 2.0
Django 2.0 came out a couple of weeks ago. It now supports "conditional aggregation" which is SQL standard I didn't even know about. Before So I have a Django app which has an endpoint that generates some human-friendly stats about the number of uploads (and their total size) in various different time intervals. First of all, this is how it set up the time intervals: today = timezone.now() start_today = today.replace(hour=0, minute=0, second=0) start_yesterday = start_today - datetime.timedelta(days=1) start_this_month = today.replace(day=1) start_this_year = start_this_month.replace(month=1) And then, for each of these, there's a little function that returns a dict for each time interval: def count_and_size(qs, start, end): sub_qs = qs.filter(created_at__gte=start, created_at__lt=end) return { 'count': sub_qs.count(), 'total_size': sub_qs.aggregate(size=Sum('size'))['size'], } numbers['uploads'] = { 'today': count_and_size(upload_qs, start_today, today), 'yesterday': count_and_size(upload_qs, start_yesterday, start_today), 'this_month': count_and_size(upload_qs, start_this_month, today), 'this_year': count_and_size(upload_qs, start_this_year, today), } What you get is exactly 2 x 4 = 8 queries. One COUNT and one SUM for each time interval. E.g. SELECT SUM("upload_upload"."size") AS "size" FROM "upload_upload" WHERE ("upload_upload"."created_at" >= ... SELECT COUNT(*) AS "__count" FROM "upload_upload" WHERE ("upload_upload"."created_at" >= ... ...6 more queries... Middle Oops. I think this code comes from a slightly rushed job. We can do the COUNT and the … -
When Docker is too slow, use your host
I have a side-project that is basically a React frontend, a Django API server and a Node universal React renderer. The killer feature is its Elasticsearch database that searches almost 2.5M large texts and 200K named objects. All the data is stored in a PostgreSQL and there's some Python code that copies that stuff over to Elasticsearch for indexing. The PostgreSQL database is about 10GB and the Elasticsearch (version 6.1.0) indices are about 6GB. It's moderately big and even though individual searches take, on average ~75ms (in production) it's hefty. At least for a side-project. On my MacBook Pro, laptop I use Docker to do development. Docker makes it really easy to run one command that starts memcached, Django, a AWS Product API Node app, create-react-app for the search and a separate create-react-app for the stats web app. At first I tried to also run PostgreSQL and Elasticsearch in Docker too, but after many attempts I had to just give up. It was too slow. Elasticsearch would keep crashing even though I extended my memory in Docker to 4GB. This very blog (www.peterbe.com) has a similar stack. Redis, PostgreSQL, Elasticsearch all running in Docker. It works great. One single docker-compose … -
Django 2.0’da gelen yenilikler ve daha fazlası!
Django 1.11.x; Python 2.7’yi destekleyen son seridir. Django; 2.0 ile artık Python 3.4, Python 3.5 ve Python 3.6’ya destek verecek. Python 3.4 ile geliştirme planlıyorsanız Django 2.0 2019 Nisan’da geliştirme bırakıp üst serilere geçiş yapılacak. Çünkü Python 3.4 için 2019 Mart’da geliştirmeyi devam edilmeyecek. Pdf halinde link : TIKLA -
Use Bitcoin to Get Two Scoops of Django at 25% Off
Like the title of this blog post says, for Bitcoin purchases we're offering a 25% discount for purchases of Two Scoops of Django. That puts the ebook version at $34.36 and the autographed hardcopy at $38.36. Pretty awesome, right? If you want to take advantage of this awesome deal, the Bitcoin discount is applied during checkout. Combining the Bitcoin Discount With the Bulk Discount Yes, the Bitcoin discount can be combined with bulk orders. So if you order 15 books or more, you get both the 20% bulk discount and the 25% bitcoin discount. That means each book is bought at $28.77 versus $47.95! Furthermore, bulk orders are shipped free to anywhere in the world. This makes it an incredible deal for companies, organizations, and user groups. Stay tuned! -
Use Bitcoin to Get Two Scoops of Django at 25% Off
Like the title of this blog post says, for Bitcoin purchases we're offering a 25% discount for purchases of Two Scoops of Django. That puts the ebook version at \$34.36 and the autographed hardcopy at \$38.36. Pretty awesome, right? If you want to take advantage of this awesome deal, the Bitcoin discount is applied during checkout. Combining the Bitcoin Discount With the Bulk Discount Yes, the Bitcoin discount can be combined with bulk orders. So if you order 15 books or more, you get both the 20% bulk discount and the 25% bitcoin discount. That means each book is bought at \$28.77 versus \$47.95! Furthermore, bulk orders are shipped free to anywhere in the world. This makes it an incredible deal for companies, organizations, and user groups. Stay tuned! -
On degrees
Lately there’s been a recurring discussion on various social-media outlets about the value and/or necessity of academic degrees to a career in programming. I’ve jumped into a few such threads on Twitter, but 140-character or (now) 280-character chunks of commentary don’t really let me do justice to the topic. Luckily, this is my blog and it obeys my rules and I can use as many characters as I like. So here’s a fuller and ... Read full entry -
On degrees
Lately there’s been a recurring discussion on various social-media outlets about the relevance of academic degrees to a career in programming. Specifically: is a degree in computer science (or some other field perceived as related) a necessity for a career as a programmer? If not, is it still a good idea to have one? I’ve jumped into a few such threads on Twitter, but I have complex thoughts on the topic, and 140-character or (now) 280-character ... Read full entry -
pytest-randomly history
My plugin pytest-randomly was recently moved into the pytest-dev organization on GitHub, making it a bit “more official” as a pytest plugin. Thanks to Bruno Oliveira for suggesting it, Florian Bruhin and Bruno for approving it on the pytest-dev mailing list, and Gordon Wrigley for helping with its development. In celebration I thought I’d explain a bit more of the background behind it. pytest-randomly really combines two functions: Controlling the random seed between test runs, which is useful when using a tool like Factory Boy to generate test data. By allowing the same seed to be used again, failures can be debugged. See more in my blog post on it. Reordering tests randomly, to discourage order-dependency, which can be common with certain fixture patterns touching global state like a database For YPlan, we needed random seed control. We added Factory Boy to shrink the test code needed to set up Django model instances, and to get more value from the tests by covering a wider range of cases between runs. We were using nose at the time, and implemented a plugin to reset the seed at the start of each test and a flag to control in just a few … -
New year, new stuff
Happy 2018 everyone! Here's a little summary of the past Evennia year and what is brewing.(Evennia is a Python server- and toolbox for creating text-based multiplayer games (MU*)).The biggest challenge for me last year Evennia-wise was the release of Evennia 0.7. Especially designing the migration process for arbitrary users migrating the Django auth-user took a lot of thought to figure out as described in my blog post here. But now 0.7 is released and a few initial minor adjustments could be made after feedback from daring pilot testers. The final process of migrating from 0.6 to 0.7 is, while involved, a step-by-step copy&paste list that has worked fine for most to follow. I've gotten far fewer questions and complains about it than could be expected so that's a good sign. Working away on the boring but important behind-the-scenes stuff made me less able to keep up with more "mundane" issues and bugs popping up, or with adding new "fun" features to existing code. Luckily the Evennia community has really been thriving this year; It feels like new users pop up in the support channel all the time now. The number of pull requests both fixing issues and offering new features … -
2018 New Years Resolutions
Happy New Year! The last time I wrote down resolutions was way back in 2014. I had done it for many years at that point, dating back to even before my old blog. Somehow I fell out of what I consider a positive habit. Well, it's time to pick it up again! So here are my resolutions for 2018: Weight down to 160. Work out for 60 minutes a day. I got lazy in the last year. Start martial arts again. Because of knee and ankle injuries, Capoeira is probably right out. Already up Kali/Escrima under Guro Mestre Xingú instead. Write at least 3 books (last year we did 5 books, so this is doable!). Out of those, one will be about coding in some way. Blog at least once a month, about anything. Python, Django, serverless coding, martial arts, whatever. And with this post, January is done! Release some coding projects I can't talk about yet. Travel outside the USA. That looks to be a trip to Colombia to speak at PyCon Colombia! If you are in South America, please meet me (and Audrey) there! I'll be sharing more details soon. :-) note: The photo is from a light … -
2018 New Years Resolutions
Happy New Year! The last time I wrote down resolutions was way back in 2014. I had done it for many years at that point, dating back to even before my old blog. Somehow I fell out of what I consider a positive habit. Well, it's time to pick it up again! So here are my resolutions for 2018: Weight down to 160. Work out for 60 minutes a day. I got lazy in the last year. Start martial arts again. Because of knee and ankle injuries, Capoeira is probably right out. Already up Kali/Escrima under Guro Mestre Xingú instead. Write at least 3 books (last year we did 5 books, so this is doable!). Out of those, one will be about coding in some way. Blog at least once a month, about anything. Python, Django, serverless coding, martial arts, whatever. And with this post, January is done! Release some coding projects I can't talk about yet. Travel outside the USA. That looks to be a trip to Colombia to speak at PyCon Colombia! If you are in South America, please meet me (and Audrey) there! I'll be sharing more details soon. :-) note: The photo is from a light …