Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
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! -
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 … -
Elm & Django #1
Here is a simple solution to run Elm code within a Django template. This could be used to handle the full frontend or just to embed a "widget" - like a search bar - via Elm. -
Elm & Django #1
Here is a simple solution to run Elm code within a Django template. This could be used to handle the full frontend or just to embed a "widget" - like a search bar - via Elm. -
Caktus Blog Best of 2017
With 2017 now over, we highlight the top 17 posts published or updated on the Caktus blog this year. Have you read them all? -
Create a Mobile Application with Ionic 3, Angular 5 and Django Rest Framework
In this tutorial, we are going to learn, step by step how to create a mobile application with an Ionic 3/Angular 5 front-end and a Python back-end. We'll be using Django and Django Rest Framework to build a simple REST API. The app we'll be creating is a simple product tracker that can be used to keep track of the quantities of the products you have in stock. You'll be able to create products, increment and decrement their quantities. In nutshell, we need to: create the Django project create the Django application design and create the database model(s) migrate the database generate the admin web interface to create, read, update and delete the database records create a super user generate a browsable and documented REST API with Django Rest Framework generate the Ionic 3 project create an Angular 5 CRUD service to interface with the REST API create an Ionic page to create and update products create an Ionic page to read the products add a method to delete products Introduction to Django Django is a Python-based web framework that encourages rapid development. It's used by many web developers create web applications using the Python language. Django has a plethora … -
Django multitenancy using Postgres Row Level Security
Quite some time ago, I did some experiments in [using Postgres Row Level Security (RLS) from within Django](http://schinckel.net/2015/12/07/row-level-security-in-postgres-and-django/). It occurred to me that this philosophy could be used to model a multi-tenant application. The main big problem with [django-boardinghouse](http://django-boardinghouse.readthedocs.io) is that you have to apply migrations to multiple schemata. With many tenants, this can take a long time. It's not easy to do this in a way that would be conducive to having limited downtime. On the other hand, RLS means that the database restricts which rows of specific tables need to be shown in a given circumstance. Normally, examples of RLS show this by using a different user, but this is not necessary. In fact, in most modern web applications, a single database user is used for all connections. This has some big benefits (in that a connection to the database can belong to a pool, and be shared by different requests). Luckily, there are other ways to have RLS applied. One method is to use Postgres' session variables. This is outlined quite well in [Application users vs. Row Level Security](https://blog.2ndquadrant.com/application-users-vs-row-level-security/). I'm going just use simple session variables, as the facility for doing this will be encapsulated, and based … -
Building Modern Django Web Applications with React and Django Rest Framework
In nutshell, in this tutorial we'll look at how to build a modern (SPA: Single Page Application) CRUD web application using Django and React.js (instead of Django built-in templates engine). We'll use Django Rest Framework to build an example API, react-router-dom for routing the front-end app, Axios for making HTTP calls (GET, POST, PUT and DELETE etc.) to the Rest API endpoints, Redux for managing the app's global state and finally Webpack to bundle the assets This tutorial will cover how to serve the React app using the Django server and how to allow the React app to communicate with the Django server over its Rest API endpoints When building a modern web application with tools such as Django and React in our case, React will take care of rendering the view layer of your app's architecure and Django will be used for communicating with the database and exposing a CRUD REST API. You can have completly separate front-end and back-end or you can also make Django serve the first page where the React app will be mounted (we'll follow this second approach in this tutorial). The communication between React and Django will be made using HTTP/Ajax requests to the … -
Building Modern Django Web Applications with React and Django Rest Framework
In nutshell, in this tutorial we'll look at how to build a modern (SPA: Single Page Application) CRUD web application using Django and React.js (instead of Django built-in templates engine). We'll use Django Rest Framework to build an example API, react-router-dom for routing the front-end app, Axios for making HTTP calls (GET, POST, PUT and DELETE etc.) to the Rest API endpoints, Redux for managing the app's global state and finally Webpack to bundle the assets This tutorial will cover how to serve the React app using the Django server and how to allow the React app to communicate with the Django server over its Rest API endpoints When building a modern web application with tools such as Django and React in our case, React will take care of rendering the view layer of your app's architecure and Django will be used for communicating with the database and exposing a CRUD REST API. You can have completly separate front-end and back-end or you can also make Django serve the first page where the React app will be mounted (we'll follow this second approach in this tutorial). The communication between React and Django will be made using HTTP/Ajax requests to the … -
REST API Basics with the Django REST Framework
This post is the same as the p...