Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
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 -
Django Tips #22 Designing Better Models
In this post, I will share some tips to help you improve the design of your Django Models. Many of those tips are related to naming conventions, which can improve a lot the readability of your code. The PEP8 is widely used in the Python ecosystem (Django included). So it’s a good idea to use it in your own projects. Besides PEP8, I like to follow Django’s Coding Style which is a guideline for people writing code for inclusion in the Django code base itself. Below, an overview of the items we are going to explore: Naming Your Models Model Style Ordering Reverse Relationships Blank and Null Fields Naming Your Models The model definition is a class, so always use CapWords convention (no underscores). E.g. User, Permission, ContentType, etc. For the model’s attributes use snake_case. E.g. first_name, last_name, etc. Example: from django.db import models class Company(models.Model): name = models.CharField(max_length=30) vat_identification_number = models.CharField(max_length=20) Always name your models using singular. Call it Company instead of Companies. A model definition is the representation of a single object (the object in this example is a company), and not a collection of companies. This usually cause confusion because we tend to think in terms of … -
The case for a Django upgrade
Like eating Brussels sprouts, everyone knows that keeping software current is good for you. But getting clients to actually upgrade regularly is hard. Why is that? It boils down to this. An upgrade costs money, sometimes a lot of money, but the result has no visible outcome. In fact, in many cases the only outcome is an assurance that you've reduced the probability of attack, intrusion, breach and related unpleasantness. By any measure, that's a tough sales pitch. It's hard to get people to pay for things they can't see. But, like eating your Brussels sprouts, it is important for good health and is part of the cost of doing business online. In an effort to provide believable ammunition to those seeking upgrade funds, we thought it might be helpful to offer some specifics. Although the following is presented through the lens of a website using Python and Django, the principles remain the same for any language or framework. Support for Django 1.8 ends in April 2018. Django is on a consistent release schedule where each third version is a long-term release, meaning it is supported longer than the others. There are plenty of good reasons to upgrade for each … -
Django QuerySet to CSV Files & Datasets
Django QuerySets to CSVs is a ... -
Facebook integration in your website
This post includes how to integrate facebook login in a website using Django. Uses of integrating facebook login: Instead of registration we use facebook login because facebook login takes less time than registration. we can get verified email ids from facebook. Post user actions on userwalls, pages, groups. Send invitations to user friends via logged in user. Send requests from your app to user. The following steps needed for integration. Creating Facebook app. Authenticating user and getting accesstoken. Get user information using accesstoken. Get user friends list. Get user pages. Get user groups. 1.Creating Facebook app: To create facebook app click here and go to apps on top of the page. Click on create new app.The resulting popup box will prompt you to enter 3 things: AppName, Namespace & category. After creating app you will be provided a dash board and grab both the app Id and app secret. Complete the all field in settings basic tab.Click Add Platform at the bottom of the page and select Website.Enter a path where you will want to store your file(i.e redirected url). 2.Authenticating user and getting accesstoken: Authentication flow contains 3 steps. i.Generates a URL asking the user for permission. ii.Facebook returns … -
Understanding Django model formsets in detail and their advanced usage.
Similar to the regular formsets, Django also provides model formset that makes it easy to work with Django models. Django model formsets provide a way to edit or create multiple model instances within a single form. Model Formsets are created by a factory method. The default factory method is modelformset_factory(). It wraps formset factory to model forms. We can also create inlineformset_factory() to edit related objects. inlineformset_factory wraps modelformset_factory to restrict the queryset and set the initial data to the instance’s related objects. Step1: Create model in models.py class User(models.Model): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) user_group = models.ForeignKey(Group) birth_date = models.DateField(blank=True, null=True) Step2: in forms.py from django.forms.models import modelformset_factory from myapp.models import User UserFormSet = modelformset_factory(User, exclude=()) This will create formset which is capable of working with data associated with User model. We can also pass the queryset data to model formset so that it can do the changes to the given queryset only. formset = UserFormSet(queryset=User.objects.filter(first_name__startswith='M')) We can produce an extra form in the template by passing 'extra' argument to the modelformset_factory method, we can use this as follows. UserFormSet = modelformset_factory(User, exclude=(), extra=1) We can customize the form that will be displayed in the … -
How to develop RESTful webservice in Django using Django REST framework?
DjangoRestFramework is widely used to develop restful API. Django REST Framework is easy to use who are familiar with Django, as it is developed on the core concepts of Django. In the current blog post we’ll learn how to develop a RESTful API that performs CRUD operations on the DB. Install Django REST famework using pip command and keep ‘rest_framework’ in your INSTALLED_APPS. Install: pip install djangorestframework In settings.py INSTALLED_APPS = ( ... 'rest_framework', ) Now lets create an application with name api and create a model called ‘Country’ on which we will perform our CRUD operations. In api/models.py from django.db import models class Country(models.Model): name = models.CharField(max_length=10) Add api to your INSTALLED_APPS. INSTALLED_APPS = ( ... 'rest_framework', ‘api’, ) Create migrations with makemigrations and migrate command which creates the tables in your DB. python manage.py makemigrations python manage.py migrate One of the important part of the djangorestframework is the serializers. Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types. Serializers also provide deserialization, allowing parsed data … -
How to Use RESTful APIs with Django
First, let’s get those terms out of our way. The REST acronym stands for Representational State Transfer, which is an architectural design. Usually when we use the term RESTful, we are referring to an application that implements the REST architectural design. API stands for Application Programming Interface, which is a software application that we interact programmatically, instead of using a graphical interface. In other words, we interact with it at a lower level at the source code, writing functions and routines. In the context of Web development, usually when we are talking about a RESTful API we are referring to Web Services (or Web APIs). It’s a common way to expose parts of your application to third-parties (external applications and Websites). It can be data-oriented, in a sense that your Web service (the RESTful API), simply make available the information you store in your databases using a common format, such as XML or JSON. This way, an external application can interact with your application and your data, without having to connect directly into your database. This way, it doesn’t matter if your database is MySQL or PostgreSQL, or if your application was written in Java or Python. But RESTful APIs … -
Implemementing Manual Schema with Django REST Framework
This is what will hopefully be the first in a series of reference articles for using Core API libraries with Django REST Framework (DRF). This is an extraction from an existing production view running Django 1.11/2.0 on Python 3.6. The original code did something else, but for contract reasons I'm demonstrating this code with sending email. Please note that this article is very terse, with almost no description, no tests, and no URL routing. Just enough code so that if you have a decent understand of DRF, you can make custom views work with Core API. First, the serializer: # serializers.py from django.core.mail import send_mail from markdown import markdown from rest_framework import serializers class EmailSerializer(serializers.Serializer): to_addresses = serializers.ListField( child=serializers.EmailField(), required=True ) from_email = serializers.EmailField(required=True) subject = serializers.CharField(required=True) message = serializers.CharField(required=True) htmlize = serializer.BooleanField(required=False, default=False) def create(self, validated_data): if validated_data['htmlize']: validated_data['html_message'] = markdown(validated_data['message']) send_mail(**validated_data) Now the view: # views.py import coreapi import coreschema from rest_framework import schemas from rest_framework.views import APIView from .serializers import EmailSerializer class EmailCreateAPIView(APIView): """ Assumes you have set permissions and authentication in `settings.py`""" serializers = EmailSerializer schema = schemas.ManualSchema(fields=[ coreapi.Field( "to_addresses", required=True, location="form", schema=coreschema.Array( description="List of email addresses" ) ), coreapi.Field( "from_email", required=True, location="form", schema=coreschema.String() ), coreapi.Field( …