Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
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... -
Building Modern Web Apps with Python, Django Rest Framework and Angular 2+
In this tutorial we are going to learn how to get started building modern web applications with Python, Django and Django Rest Framework as the back-end stack and the new Google Framework, Angular 2+, to build JavaScript client side applications, as the front-end technology. We'll see how to integrate both frameworks in the development and the production environments and how to use the Angular HTTP module to make API calls or Ajax requests to our REST API back-end. This tutorial is using the old Angular HTTP client for making HTTP calls. This module is deprecated in Angular 5 and will be replaced by the new Angular HttpClient module available in Angular 4.3+ which comes with many new features such as the HTTP interceptors. The two modules have the same API interface so you should be able to easily migrate to the new one. In future tutorials we will be using HttpClient so stay tuned! The Angular CLI is a command line utility which allows you to quickly generate and build Angular 2+ apps without the hassle of WebPack configuration. The CLI takes care of the configuration and let you focus on build your next Angular app. It's a really great … -
Building APIs with Django and GraphQL
This tutorial will introduce you to GraphQL with Python, Django and Graphene. We'll see how to create a simple Django project to demonstrate how to build an API server based on GraphQL (instead of REST) then we'll see how to use graphiql_django, an interface for testing GraphQL queries and mutations before building your front-end application, to send GraphQL Queries (for getting data) and Mutations (for posting and updating data). In this part we'll be dealing with building the backend. In the next tutorials we will see how to use frameworks and libraries such as Angular and React to build a front-end application that consumes and updates our GraphQL server and advanced use cases such as user authentication, permissions and Relay Make sure to follow me on twitter (@techiediaries) to be notified once the next tutorial parts are ready. GraphQL is a modern API standard for building Web APIs, invented and used internally by Facebook for its native mobile applications then later open sourced. GraphQL provides a better, powerful and flexible alternative to REST. Before we dive into GraphQL concepts, let's understand what's REST: REST stands for Representational State Transfer and it's an architectural pattern for designing client/server distributed systems. Unlike … -
Building Django HTTP APIs with GraphQL and Graphene
This tutorial will introduce you to GraphQL with Python, Django and Graphene. We'll see how to create a simple Django project to demonstrate how to build an API server based on GraphQL (instead of REST) then we'll see how to use graphiql_django, an interface for testing GraphQL queries and mutations before building your front-end application, to send GraphQL Queries (for getting data) and Mutations (for posting and updating data). In this part we'll be dealing with building the backend. In the next tutorials we will see how to use frameworks and libraries such as Angular and React to build a front-end application that consumes and updates our GraphQL server and advanced use cases such as user authentication, permissions and Relay Make sure to follow me on twitter (@techiediaries) to be notified once the next tutorial parts are ready. GraphQL is a modern API standard for building Web APIs, invented and used internally by Facebook for its native mobile applications then later open sourced. GraphQL provides a better, powerful and flexible alternative to REST. Before we dive into GraphQL concepts, let's understand what's REST: REST stands for Representational State Transfer and it's an architectural pattern for designing client/server distributed systems. Unlike … -
Building APIs with Django, GraphQL and Graphene
This tutorial will introduce you to GraphQL with Python, Django and Graphene. We'll see how to create a simple Django project to demonstrate how to build an API server based on GraphQL (instead of REST) then we'll see how to use graphiql_django, an interface for testing GraphQL queries and mutations before building your front-end application, to send GraphQL Queries (for getting data) and Mutations (for posting and updating data). In this part we'll be dealing with building the backend. In the next tutorials we will see how to use frameworks and libraries such as Angular and React to build a front-end application that consumes and updates our GraphQL server and advanced use cases such as user authentication, permissions and Relay Make sure to follow me on twitter (@techiediaries) to be notified once the next tutorial parts are ready. GraphQL is a modern API standard for building Web APIs, invented and used internally by Facebook for its native mobile applications then later open sourced. GraphQL provides a better, powerful and flexible alternative to REST. Before we dive into GraphQL concepts, let's understand what's REST: REST stands for Representational State Transfer and it's an architectural pattern for designing client/server distributed systems. Unlike … -
Django Quiz 2017
Yesterday evening I gave a quiz at the London Django Meetup Group for the second year running. Here it is so you can do it at home (no cheating!). Answers are at the bottom. Part 1: Trivia 1. What species is Django’s unofficial spirit animal? Pegasus Unicorn Pony Seal Dolphin Elephant 2. Djangocon EU this year was in… Bologna Genoa Venice Florence 3. What does LTS stand for? Long Tail Support Long Term Support Life Time Support Life Term Support 4. What does WSGI stand for? Web Socket Gateway Interface Web Server Gateway Interface Web Server Gated Interface WebS GuardIan 5. What does ACID stand for? Atomicity Consistency Integrity Durability Atomicity Concurrency Isolation Durability Atomicity Consistency Isolation Durability All Carefully Inserted Data 6. When was the first commit on Django? One point for year, one for month, one for day 7. When was the first commit in Python? One point for year, one for month, one for day 8. What is the name of the current Django fellow? One point for first name, one for last Part 2: Coding with Django 1. What’s the import for the new Django 2.0 URL syntax? from django.paths import url from django.urls import path … -
Django REST Framework Authentication by Example with JSON Web Tokens (JWT)
Introduction Django Rest Framework provides multiple mechanisms for authenticating users, in case you are new to this concept then simply put: authentication is the process of verifying the identity of users, while authorization is identifying if the user has authorized access to some server resource. In this tutorial, we are going to see what's the available mechanisms, in DRF, to authenticate users? What is the difference between DRF built-in token-based authentication system and JWT authentication? And how to add JSON Web Tokens authentication to Django Rest Framework? Different Ways to Authenticate Users? The general process of authenticating a user is done by simply checking if any user information or credentials are attached to an incoming (from the client) request. DRF has already three mechanisms to authenticate users. Let's look at each one of them: Basic authentication: It's very easy to setup but it's only recommended for testing purposes not for production. It's implemented in rest_framework.authentication.BasicAuthentication class and works by base64 encoding the user login information i.e the user's name and the password then attach them to an HTTP Authorization Header (can then be retrieved from request.META.HTTP_ AUTHORIZATION). Session based authentication: The traditional authentication mechanism and the default one used by …