Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Building a Modern Web Application with Django REST Framework and Vue: Building Views and REST API
Throughout this part of these tutorial series you will continue developing a CRUD (Create, Read, Update and Delete) application with a restful API back-end and a Vue front-end using Django, Django REST framework and Vue (with Axios as an HTTP client). In this part you'll specifically build the REST API and the front-end views to consume and display data from the API endpoints. You will also see how to integrate your Vue application with your Django back-end in production. As always you can find the source code of the demo project in this Github repository. You can check the second article from this link Summary This article is composed of the following sections: Building the REST API: You will create a simple REST API around one model (Product) with DRF and learn how to add pagination to your APIs. Creating the Service to Consume the API: You will create the class that interfaces with your API using Axios. Creating the Front End Views: You will create different views and routes for the Vue application and see how you can protect some routes from non authenticated users. Getting Ready for Production: Finally you'll prepare your app for production by tweaking some … -
Django REST Framework Read & Write Serializers
Django REST Framework (DRF) is a terrific tool for creating very flexible REST APIs. It has a lot of built-in features like pagination, search, filters, throttling, and many other things developers usually don't like to worry about. And it also lets you easily customize everything so you can make your API work the way you want. There are many gene -
csso and django-pipeline
This is a quick-and-dirty how-to on how to use csso to handle the minification/compression of CSS in django-pipeline. First create a file called compressors.py somewhere in your project. Make it something like this: import subprocess from pipeline.compressors import CompressorBase from django.conf import settings class CSSOCompressor(CompressorBase): def compress_css(self, css): proc = subprocess.Popen( [ settings.PIPELINE['CSSO_BINARY'], '--restructure-off' ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, ) css_out = proc.communicate( input=css.encode('utf-8') )[0].decode('utf-8') # was_size = len(css) # new_size = len(css_out) # print('FROM {} to {} Saved {} ({!r})'.format( # was_size, # new_size, # was_size - new_size, # css_out[:50] # )) return css_out In your settings.py where you configure django-pipeline make it something like this: PIPELINE = { 'STYLESHEETS': PIPELINE_CSS, 'JAVASCRIPT': PIPELINE_JS, # These two important lines. 'CSSO_BINARY': path('node_modules/.bin/csso'), # Adjust the dotted path name to where you put your compressors.py 'CSS_COMPRESSOR': 'peterbecom.compressors.CSSOCompressor', 'JS_COMPRESSOR': ... Next, install csso-cli in your project root (where you have the package.json). It's a bit confusing. The main package is called csso but to have a command line app you need to install csso-cli and when that's been installed you'll have a command line app called csso. $ yarn add csso-cli or $ npm i --save csso-cli Check that it installed: $ ./node_modules/.bin/csso --version 3.5.0 … -
How to add Wagtail page programmatically via Python script
Given: Two Wagtail CMS page classes: class Section(Page): subtitle = models.Charfield(max_length=128) class News(Page): content = models.Textfield() Task: Using a python script, add a News page item under the Section page titled "Latest news." Solution: 1) Get parent page instance: parent_page = Page.objects.get(title='Latest news' ... Read now -
Basics of Django Rest Framework
What Is Django Rest Framework? Django Rest Framework (DRF) is a library which works with standard Django models to build a flexible and powerful API for your project. Basic Architecture A DRF API is composed of 3 layers: the serializer, the viewset, and the router. Serializer: converts the information stored in the database and defined by the Django models into a format which is more easily transmitted via an API Viewset: defines the functions (read, create, update, delete) which will be available via the API Router: defines the URLs which will provide access to each viewset Serializers Django models intuitively represent data stored in your database, but an API will need to transmit information in a less complex structure. While your data will be represented as instances of your Model classes in your Python code, it needs to be translated into a format like JSON in order to be communicated over an API. The DRF serializer handles this translation. When a user submits information (such as creating a new instance) through the API, the serializer takes the data, validates it, and converts it into something Django can slot into a Model instance. Similarly, when a user accesses information via the … -
Container Runtimes Part 2: Anatomy of a Low-Level Container Runtime
This is the second in a four-part series on container runtimes. In part 1, I gave an overview of container runtimes and discussed the differences between low-level and high-level runtimes. In this post I will go into detail on low- level container runtimes. Low-level runtimes have a limited feature set and typically perform the low- level tasks for running a container. Most developers shouldn't use them for their day-to-day work. Low-level runtimes are usually implemented as simple tools or libraries that developers of higher level runtimes and tools can use for the low-level features. W[...] -
Container Runtimes Part 2: Anatomy of a Low-Level Container Runtime
This is the second in a four-part series on container runtimes. In part 1, I gave an overview of container runtimes and discussed the differences between low-level and high-level runtimes. In this post I will go into detail on low- level container runtimes. Low-level runtimes have a limited feature set and typically perform the low- level tasks for running a container. Most developers shouldn't use them for their day-to-day work. Low-level runtimes are usually implemented as simple tools or libraries that developers of higher level runtimes and tools can use for the low-level features. W[...] -
Synchronizing Django model definitions
This is about a small problem we faced with the models used for customers in YPlan, now Time Out Checkout. Customers are stored in two models: Customer for active customers, and RemovedCustomer for inactive customers. When a customer closes their account, a subset of the fields are copied to RemovedCustomer, to comply with data retention policies, and then the original Customer is wiped. The two models are defined something like this: class Customer(models.Model): name = models.CharField(max_length=128, blank=True) email = models.CharField(max_length=128, null=True, unique=True) # etc. class RemovedCustomer(models.Model): name = models.CharField(max_length=128, blank=True) email = models.CharField(max_length=128, null=True) # etc. name and email are two of the fields copied on closure - they’re nearly identical, except RemovedCustomer.email is not unique, because the same email address could be used for multiple accounts that get removed one after another. The problem we faced was keeping the definitions of these fields synchronized, differences like unique asides. Initially the two model classes were declared in the usual way, as above, with the field definitions copy-pasted. This meant that changes to one model needed copying to the other. Unfortunately this got forgotten when a field on Customer had its max_length extended, so it wasn’t copied to RemovedCustomer, and the … -
Raspberry Pi Awesome // Install Scripts for Python 3, OpenCV, Dli & Others
I've found setting up my Raspb... -
On Django's longevity
“Django is about to be a teenager.” I don’t remember exactly who said that, but it came up in a discussion of potential followup events to 2015’s “Django Birthday”, held in Lawrence, Kansas, to celebrate the tenth anniversary of Django’s initial public release. There might still be some parties to throw — maybe a Django sweet sixteen — but regardless of what the future holds, the summer of 2018 will mark thirteen years since ... Read full entry -
Raspberry Pi Network Server Guide with Django & SSH
In this post, we'll be setting... -
OpenCV & Python // Web Camera Quick Test
This post assumes you have eit... -
Install OpenCV 3 for Python on Windows
OpenCV, aka Open Computer Visi... -
My Python Development Environment, 2018 Edition
This is out of date. For a newer version, see My Python Development Environment, 2020 Edition For years I’ve noodled around with various setups for a Python development environment, and never really found something I loved – until now. My setup pieces together pyenv, pipenv, and pipsi. It’s probably a tad more complex that is ideal for most Python users, but for the things I need, it’s perfect. My Requirements I do have somewhat specific (maybe unusual? -
Django development with Docker —A completed development cycle
After finishing the last post about Django development with Docker, we got a host-isolated development environment, which allows us to encapsulate our application and dependencies. Let’s review some tips and improvements for our environment.IntroductionUsually on our development environment, we can access to the local database, install different requirements, reload the running server on code changes, use different settings or running different commands. If we cannot do that, our development cycle could be slow and tedious.In order to solve that, we need to implement these features:Accessing the containers database (Using ports )Installing different requirements or using different settings (Using ARG and ENV )Reloading the running server on code changes (Using volumes)Accessing the database(Thanks Dilip Maharjan for inspiring this part)From our last post, this is our configuration. Our database service definition in compose looks like:https://medium.com/media/35df038b3b4523db615116fe32f5fca4/hrefAnd our Django settings looks like:https://medium.com/media/a86b17b1eb6442fa8f29b23b4e0aed22/hrefFrom time to time, you might want to access the database directly, but we cannot access to the database container directly from outside the django container.The Django application inside the container can access to the database container because they are in the same network and Docker has a feature called “automatic service discovery”, which resolves “db” to an IP of that network. Read … -
Continuous Integration and Deployment with Drone, Docker, Django, Gunicorn and Nginx - Part 3
The Introduction This is the third and final part of a multi-part tutorial covering a simple(ish) setup of a continuous integration/deployment pipeline using Drone.io:0.5. Since Part 2, Drone.io:0.8 has become available. This new version boasts much better documentation and is comparably much easier to set up than Drone.io:0.5 and even outlines how to set up your server behind NGINX. In parts 1 and 2 of this series we: Set up our Drone server Added a .drone.yml to our Django application and configured it to tell Drone to run our application’s test suite Added a condition on our master branch to only allow passed build to be merged Added a publish step to our .drone.yml to be triggered on merges to publish an updated version of our application’s code to Dockerhub Created a systemd service to manage our application’s Docker container on our EC2 instance Created a deploy.sh script on our EC2 instance that stops and removes our app’s Docker container, pulls an updated image for the container from Dockerhub and then restarts the systemd service managing the container. Lastly, we added a deploy step to our .drone.yml to ssh into our EC2 container and run the deploy.sh script. The last … -
How to Hide And Auto-populate Title Field of a Page in Wagtail CMS
Given from django.db import models from wagtail.wagtailsnippets.models import register_snippet class CountryPage(Page): country = models.ForeignKey('Country', blank=False, null=True, unique=True) class Country(models.Model): name = models.CharField(max_length=128) Task I want to have the title field of my CountryPage to be auto-populated with a ... Read now -
Django Single Sign On(SSO) to multiple applications
Single sign on is a way for users to issue a security token for the first time login, login into multiple applications using one set of credentials i.e security token. Adding sso to an application will make things easier for users, because they dont need to remember login credentials for multiple applications. User just need to enter their login credentials for first time instead of re-entering their credentials for every application login. In this post, we'll see how to add single sign on to multiple django applications using django-simple-sso. Using django-simple-sso, we should have single server, multiple clients. 1. Server will have all users information which'll authenticate user details at the time of login, creates token for the first time. Using their security tokens, it'll authenticates user details 2. Each Client or application needs to generate their public key, private key in the server to perform requests securely. How Django SSO works for multiple applications? User --> application -- > SSO Server --> application 1. When User log into an application, the client will send a request with next GET parameter, which have redirect url after successful login 2. Request details(application details: public key, private key, redirect url) will be … -
Add Value To Your Django Project With An API
How do your users interact with your web app? Do you have users who are requesting new features? Are there more good feature requests than you have developer hours to build? Often, a small addition to your app can open the door to let users build features they want (within limits) without using more of your own developers’ time, and you can still keep control over how data can be accessed or changed. That small addition is called an application programming interface, or API. APIs are used across the web, but if you aren’t a developer, you may not have heard of them. They can be easily built on top of Django projects, though, and can provide great value to your own developers as well as to your users. What Is An API? At its core, an API is essentially an interface which allows two pieces of software to talk to each other. This usually refers to a request that reaches across the web to a third-party service, although it can also be used to allow two of your own apps to talk to each other. Why Would I Want One? As a user, there are many reasons you might … -
Running Django Web Apps On Android Devices
When deploying a django webapp to Linux servers, Nginx/Apache as server, PostgreSQL/MySQL as database are preferred. For this tutorial, we will be using django development server with SQLite database. First install SSHDroid app on Android. It will start ssh server on port 2222. If android phone is rooted, we can run ssh on port 22. Now install QPython. This comes bundled with pip, which will install required python packages. Instead of installing these two apps, we can use Termux, GNURoot Debian or some other app which provides Linux environment in Android. These apps will provide apt package manager, which can install python and openssh-server packages. I have used django-bookmarks, a simple CRUD app to test this setup. We can use rsync or adb shell to copy django project to android. rsync -razP django-bookmarks :$USER@$HOST:/data/local/ Now ssh into android, install django and start django server. $ ssh -v $USER@$HOST $ python -m pip install django $ cd /data/local/django-bookmarks $ python manage.py runvserver This will start development server on port 8000. To share this webapp with others, we will expose it with serveo. $ ssh -R 80:localhost:8000 serveo.net Forwarding HTTP traffic from https://incepro.serveo.net Press g to start a GUI session and ctrl-c … -
Running Django Web Apps On Android Devices
When deploying a django webapp to Linux servers, Nginx/Apache as server, PostgreSQL/MySQL as database are preferred. For this tutorial, we will be using django development server with SQLite database. First install SSHDroid app on Android. It will start ssh server on port 2222. If android phone is rooted, we can run ssh on port 22. Now install QPython. This comes bundled with pip, which will install required python packages. Instead of installing these two apps, we can use Termux, GNURoot Debian or some other app which provides Linux environment in Android. These apps will provide apt package manager, which can install python and openssh-server packages. I have used django-bookmarks, a simple CRUD app to test this setup. We can use rsync or adb shell to copy django project to android. rsync -razP django-bookmarks :$USER@$HOST:/data/local/ Now ssh into android, install django and start django server. $ ssh -v $USER@$HOST $ python -m pip install django $ cd /data/local/django-bookmarks $ python manage.py runvserver This will start development server on port 8000. To share this webapp with others, we will expose it with serveo. $ ssh -R 80:localhost:8000 serveo.net Forwarding HTTP traffic from https://incepro.serveo.net Press g to start a GUI session and ctrl-c … -
Running Django Web Apps On Android Devices
When deploying a django webapp to Linux servers, Nginx/Apache as server, PostgreSQL/MySQL as database are preferred. For this tutorial, we will be using django development server with SQLite database. First install SSHDroid app on Android. It will start ssh server on port 2222. If android phone is rooted, we can run ssh on port 22. Now install QPython. This comes bundled with pip, which will install required python packages. Instead of installing these two apps, we can use Termux, GNURoot Debian or some other app which provides Linux environment in Android. These apps will provide apt package manager, which can install python and openssh-server packages. I have used django-bookmarks, a simple CRUD app to test this setup. We can use rsync or adb shell to copy django project to android. rsync -razP django-bookmarks :$USER@$HOST:/data/local/ Now ssh into android, install django and start django server. $ ssh -v $USER@$HOST $ python -m pip install django $ cd /data/local/django-bookmarks $ python manage.py runvserver This will start development server on port 8000. To share this webapp with others, we will expose it with serveo. $ ssh -R 80:localhost:8000 serveo.net Forwarding HTTP traffic from https://incepro.serveo.net Press g to start a GUI session and ctrl-c … -
Deep Learning Acronym Cheatsheet
Below as a list I'm working on... -
Let's talk about usernames
A few weeks ago I released django-registration 2.4.1. The 2.4 series is the last in the django-registration 2.x line, and from here on out it’ll only get bugfixes. The master branch is now prepping for 3.0, which will deprecate a lot of the cruft that’s accumulated over the past decade of maintaining it, and try to focus on best practices for modern Django applications. I’ll write more about that sometime soon ... Read full entry -
Let's talk about usernames
A few weeks ago I released django-registration 2.4.1. The 2.4 series is the last in the django-registration 2.x line, and from here on out it’ll only get bugfixes. The master branch is now prepping for 3.0, which will remove a lot of the deprecated cruft that’s accumulated over the past decade of maintaining it, and try to focus on best practices for modern Django applications. I’ll write more about that sometime ... Read full entry