Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Celery + Redis + Django
*Celery* is a task queue with ... -
Hosting Django Sites on Amazon Elastic Beanstalk
Introduction Amazon Web Services (AWS)' Elastic Beanstalk is a service that bundles up a number of their lower-level services to manage many details for you when deploying a site. We particularly like it for deploys and autoscaling. -
Fossgis: sewer cadastre with qgis - jörg Höttges
(One of my summaries of a talk at the 2017 fossgis conference). With engineer firms from the Aachen region they created qkan. Qkan is: A data structure. Plugins for Qgis. Direct access. Not a specific application with restricted access, but unrestricted access from within Qgis. (He noticed lots of interest among the engineers to learn qgis during the project!) It has been designed for the needs of the engineers that have to work with the data. You first import the data from the local sewer database. Qkan converts the data to what it needs. Then you can do simulations in a separate package. The results of the simulation will be visualized by Qkan in qgis. Afterwards you probably have to make some corrections to the data and give corrections back to the original database. Often you have to go look at the actual sewers to make sure the database is correct. Output is often a map with the sewer system. Some functionality: import sewer data (in various formats). Simulate water levels. Draw graphs of the water levels in a sewer. Support database-level check ("an end node cannot occur halfway a sewer"). They took care to make the database schema simple. … -
Fossgis: open source for emergencies - Marco Lechner
(One of my summaries of a talk at the 2017 fossgis conference). He works for the Bundesamtes fuer Strahlenschutz, basically the government agency that was started after Chernobil to protect against and to measure radioactivity. The software system they use/build is called IMIS. IMIS consists of three parts: Measurements (automatic + mobile measurements + laboratory results). Prediction system. Including documentation (managed in Plone, a python CMS system). Decision support. Help support the government layers that have to make the decisions. They have a simple map at odlinfo.bfs.de. The current core of the system is proprietary. They are dependent on one single firm. The system is heavily customized for their usage. They need a new system because geographical analysis keeps getting more important and because there are new requirements coming out of the government. The current program cannot handle that. What they want is a new system that is as simple as possible; that uses standards for geographical exchange; they don't want to be dependent on a single firm anymore. So: Use open standards, so OGC. But also a specific world-wide nuclear info protocol. Use existing open source software. OSGEO. If we need something special, can we change/extend existing open source … -
The Top 5 Most Used Django Commands and what they mean.
Django command line commands a... -
Ask Vitor #2: How to dynamically filter ModelChoice's queryset in a ModelForm?
Michał Strumecki asks: I just want to filter select field in a form, regarding a currently logged user. Every user has own categories and budgets. I want to display only a models related with a currently logged user. I’ve tried stuff with filtering before is_valid field, but with no result. Answer This is a very common use case when dealing with ModelForms. The problem is that in the form fields ModelChoice and ModelMultipleChoiceField, which are used respectively for the model fields ForeignKey and ManyToManyField, it defaults the queryset to the Model.objects.all(). If the filtering was static, you could simply pass a filtered queryset in the form definition, like Model.objects.filter(status='pending'). When the filtering parameter is dynamic, we need to do a few tweaks in the form to get the right queryset. Let’s simplify the scenario a little bit. We have the Django User model, a Category model and Product model. Now let’s say it’s a multi-user application. And each user can only see the products they create, and naturally only use the categories they own. models.py from django.contrib.auth.models import User from django.db import models class Category(models.Model): name = models.CharField(max_length=30) user = models.ForeignKey(User, on_delete=models.CASCADE) class Product(models.Model): name = models.CharField(max_length=30) price = models.DecimalField(decimal_places=2, … -
Fossgis: creating maps with open street map in QGis - Axel Heinemann
(One of my summaries of a talk at the 2017 fossgis conference). He wanted to make a map for a local run. He wanted a nice map with the route and the infrastructure (start, end, parking, etc). Instead of the usual not-quite-readable city plan with a simple line on top. With qgis and openstreetmap he should be able to make something better! A quick try with QGis, combined with the standard openstreetmap base map, already looked quite nice, but he wanted to do more customizations on the map colors. So he needed to download the openstreetmap data. That turned into quite a challenge. He tried two plugins: OSMDownloader: easy selection, quick download. Drawback: too many objects as you cannot filter. The attribute table is hard to read. QuickOSM: key/value selection, quick. Drawback: you need a bit of experience with the tool, as it is easy to forget key/values. He then landed on https://overpass-turbo.eu . The user interface is very friendly. There is a wizard to get common cases done. And you can browse the available tags. With the data downloaded with overpass-turbo, he could easily adjust colors and get a much nicer map out of it. You can get it … -
Fossgis: introduction on some open source software packages
(One of my summaries of a talk at the 2017 fossgis conference). The conference started with a quick introduction on several open source programs. Openlayers 3 - Marc Jansen Marc works on both openlayers and GeoExt. Openlayers is a javascript library with lots and lots of features. To see what it can do, look at the 161 examples on the website :-) It works with both vector layers and raster layers. Openlayers is a quite mature project, the first version is from 2006. It changed a lot to keep up with the state of the art. But they did take care to keep everything backwards compatible. Upgrading from 2.0 to 2.2 should have been relatively easy. The 4.0.0 version came out last month. Openlayers... Allows many different data sources and layer types. Has build-in interaction and controls. Is very actively developed. Is well documented and has lots of examples. The aim is to be easy to start with, but also to allow full control of your map and all sorts of customization. Geoserver - Marc Jansen (Again Marc: someone was sick...) Geoserver is a java-based server for geographical data. It support lots of OGC standards (WMS, WFS, WPS, etc). Flexible, … -
Continuous Integration and Deployment with Drone, Docker, Django, Gunicorn and Nginx - Part 1
Part 1: Continuous Integration and Deployment With Drone, Docker, Django, Gunicorn and Nginx The Introduction This is the first part in a multi-part tutorial covering a simple(ish) setup of a continuous integration/deployment pipeline using Drone.io . In Part 1 we will set up some simple automated testing for a Django, Docker/Docker-Compose application. Who is tutorial this for? This tutorial is for anyone who is still somewhat new to web development and is looking for an excuse to set up a relatively simple continuous integration/delivery pipeline. I’m going to assume a basic understanding of Amazon Web Services , Docker , Gunicorn , Nginx and some familirity with Django . The basic outline of the pipeline is as follows: 1) After opening a pull request on your Github repo, a webhook will queue up a drone build for a drone agent to pick up, build your specified environment outlined in your projects .drone.yml , run any tests your project has before finally reporting back its status to Github. 2) After tests have passed and the new code has been merged in, the same webhook will queue up another build on the drone server. This time, after building and testing your application, drone … -
Class-Based Views vs. Function-Based Views
If you follow my content here in the blog, you probably have already noticed that I’m a big fan of function-based views. Quite often I use them in my examples. I get asked a lot why I don’t use class-based views more frequently. So I thought about sharing my thoughts about that subject matter. Before reading, keep that in mind: class-based views does not replace function-based views. Introduction I’m not an old school Django developer that used it when there was only function-based views and watched the class-based views been released. But, there was a time that only function-based views existed. I guess it didn’t take long until all sort of hacks and solutions was created to extend and reuse views, make them more generic. There was a time that function-based generic views was a thing. They were created to address the common use cases. But the problem was that they were quite simple, and was very hard to extend or customize them (other than using configurations parameters). To address those issues, the class-based views was created. Now, views are always functions. Even class-based views. When we add them to the URL conf using the View.as_view() class method, it returns … -
Django Admin: Expensive COUNT(*) Queries
If you are a Django developer, it is very likely that you use the Django Admin regularly. And if you have maintained a website with a huge amount of data, you probably already know that Django Admin can become very slow when the database table gets so large. If you log the SQL queries (either using Django logging or using Django Debug Toolbar), you would notice a very expensive SQL query, something like this: SELECT COUNT(*) AS "__count" FROM "table_name" In the default settings, you will actually notice this query twice. If you use Django Debug Toolbar, it will tell you that the query was duplicated 2 times. Issue - 1 By default ModelAdmin has show_full_result_count = True which shows the full result count in the admin interface. This is the source of one of the count(*) queries. To fix that, we just need to set this on our ModelAdmin: show_full_result_count = False Issue - 2 Even after switching show_full_result_count off, we are still noticing a count(*) query in the log. It’s because the Django Paginator does a count itself. The solution is to somehow bypass the expensive query while still returning a number so the pagination works as expected. … -
Ask Vitor #1: Getting form data to appear in URL and for use in the next view
Devon Moore asks: I want to have the user specify a date in a custom form. This date will append the current URL with the date value path/YYYY-MM-DD/ I then need to capture the date and use it to filter data from the database to display that date’s data. I’m using class based views and for the report I’m using generic view since this view is a custom report I’m building using multiple db models. Answer Here is what Devon wants to achieve: There are a couple of ways to achieve the desired result. Using class-based views, we could perhaps do something like this: forms.py class ReportForm(forms.Form): date = forms.DateField() urls.py from django.conf.urls import url from core import views # import your views using the correct app name urlpatterns = [ url(r'report/$', views.Report.as_view(), name='report'), url(r'report/(?P<year>[0-9]{4})-(?P<month>[0-9]{2})-(?P<day>[0-9]{2})/$', views.ReportDetails.as_view(), name='report_details'), ] Example of valid URL matching the report_details pattern: /report/2017-03-17/. If you want to change the URL to use slashes instead of dashes (/report/2017/03/17/), change the URL pattern to this: url(r'report/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day>[0-9]{2})/$', views.ReportDetails.as_view(), name='report_details'), views.py from django.contrib.auth.models import User from django.views import View from django.views.generic.edit import FormView from django.utils.dateformat import format class Report(FormView): template_name = 'report.html' form_class = ReportForm def form_valid(self, form): date = … -
How to Create Django Admin List Actions
Django Admin list actions are meant to be used to perform operations in bulk. All Django Admin list views already come with a default action “Delete selected <ModelName>s”. In this short tutorial I will guide you through the steps to create your own list actions. Creating the Action Function Each action in the list is a regular Python function that takes three parameters: the current ModelAdmin, a HttpRequest object (just like a view function) and a QuerySet, which is the list of selected model instances. Those Action Functions can live inside the admin.py module of your app. But if they start to get really big, you can define them outside the admin.py. Following is the skeleton for a Action Function: def my_admin_action(modeladmin, request, queryset): # do something with the queryset my_admin_action.short_description = 'My admin action' Simple Example Consider the following model and model admin: models.py from django.db import models class Book(models.Model): HARDCOVER = 1 PAPERBACK = 2 EBOOK = 3 BOOK_TYPES = ( (HARDCOVER, 'Hardcover'), (PAPERBACK, 'Paperback'), (EBOOK, 'E-book'), ) title = models.CharField(max_length=50) publication_date = models.DateField(null=True) author = models.CharField(max_length=30, blank=True) price = models.DecimalField(max_digits=5, decimal_places=2) pages = models.IntegerField(blank=True, null=True) book_type = models.PositiveSmallIntegerField(choices=BOOK_TYPES) class Meta: verbose_name = 'book' verbose_name_plural = 'books' admin.py … -
How Do I Start Learning Django
If you have done django for any amount of time you have probably gotten this question, and it can sometimes be hard to answer beyond start at the main django site. In this video I attempt to help by giving people a starting point, and some guidance on resources to and how to use. Give it a watch and offer any suggestions, and tweaks you think should be made. How Do I Start Learning Django? -
Here's a Production-Ready Dockerfile for Your Python/Django App
Update (October 29, 2019): I updated this post with more recent Django and Postgres versions, to use Python and pip directly in the container (instead of in a separate virtual environment, which was unnecessary), and switched to a non-root user via Docker instead of uWSGI. -
How to Create Infinite Scroll With Django
In this tutorial I will show you how to implement a very simple infinite scrolling with Django. Basically we will take advantage of Django’s pagination API and a jQuery plug-in. You will find examples using both function-based views and class-based views. Dependencies We don’t need anything other than Django installed in the back-end. For this example you will need jQuery and Waypoints. jQuery 3.1.1 Waypoints After downloading the dependencies, include the following scripts in your template: base.html <script src="{% static 'js/jquery-3.1.1.min.js' %}"></script> <script src="{% static 'js/jquery.waypoints.min.js' %}"></script> <script src="{% static 'js/infinite.min.js' %}"></script> Basic Example This example uses function-based view and I’m simply paginating a list of numbers, which I generate on the fly. urls.py from django.conf.urls import url from mysite.blog import views urlpatterns = [ url(r'^$', views.home, name='home'), ] views.py from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.shortcuts import render def home(request): numbers_list = range(1, 1000) page = request.GET.get('page', 1) paginator = Paginator(numbers_list, 20) try: numbers = paginator.page(page) except PageNotAnInteger: numbers = paginator.page(1) except EmptyPage: numbers = paginator.page(paginator.num_pages) return render(request, 'blog/home.html', {'numbers': numbers}) Here in this view, numbers_list represents a list of 1000 numbers, which I’m breaking down into blocks of 20 numbers per page. After paginating it, I return … -
Django 101 – App Oluşturma ve Model’a Giriş #3
Video Icerisindekiler: – Django için standart ayar düzenlemeleri. – Django App oluşturma. – Migrate ve Makemigrations kavramları. – Classlar için default kavramı ve yeniden düzenleme aşamasında karşılaşılacak sorunların giderilmesi. – Django image için gerekli ayarlamalar. – Django admine erişim. Django 101 – App Oluşturma ve Model’a Giriş #3 yazısı ilk önce Python Türkiye üzerinde ortaya çıktı. -
Django 101 – App Oluşturma ve Model’a Giriş #3
Video Icerisindekiler: – Django için standart ayar düzenlemeleri. – Django App oluşturma. – Migrate ve Makemigrations kavramları. – Classlar için default kavramı ve yeniden düzenleme aşamasında karşılaşılacak sorunların giderilmesi. – Django image için gerekli ayarlamalar. – Django admine erişim. -
Django Likes
# Django Likes Learn how to c... -
Why care about deployment?
Do you know that in Heroku you can enter a single command and have your Django project deployed for you? If there are services that have commoditized deployment, why should you care about nginx, Apache, PostgreSQL, Gunicorn, systemd, and all that, and don’t you spend your time and grey matter on something more useful? I asked the question both to myself and to my readers, and here are my conclusions, in no particular order: Some customers have a policy to use their own infrastructure. Sometimes there is a preference or policy for deploying on infrastructure hosted in a specific country; for example, I have deployed a Greek national project which had to be hosted in Greece. Sometimes it’s cheaper to deploy yourself than to deploy on Heroku, even if you take into account the time required to learn/do it. If you use a deployment service like Heroku you have vendor lock-in. If you deploy yourself you can be more flexible if your needs change. Students learn about compilers and build primitive processors not because they will work in compilers or in hardware, but because the increased understanding of their tools helps them be a better engineer. Likewise, you need to … -
Release 0.11.
We just released LFS 0.11. Changes Adds Django 1.10 support Excludes variants from sitemap Add appending slash to all urls Use F() expressions to update stock amount (#203) Use F() expression to increase use_amount for vouchers (#202) Removes django-pagination (use Django's default one instead) remove STATIC_URL (user static_url tag instead) fix saving properties and variant prices [pigletto] Information You can find more information and help on following locations: Documentation on PyPI Demo Releases on PyPI Source code on bitbucket.org and github. Google Group lfsproject on Twitter IRC -
Quickly and Easily Way to Create a Django Application: BeDjango Starter
BeDjango starter In the following post we will talk about the starter we have released from BeDjango. The decisions we have made, the features we have decided to add and some aspects that we would like to emphasize: Why did we decide to make a starter? Although starting a project in Django is a fairly quick and easy process, after developing several applications, we realized that we used to invest a certain amount of time in each project to implement similar features (registry, basic views, validations, configuration of libraries ...) Therebefore, we decided to invest that time in making a starter that we could easily reuse ... But the thing went out of hand and we created a fairly complete Django base application. Architecture We decided to modify the initial structure of folders and files that gives us django, many of these files are already being used by the community: We would like to point out that we have added a 'logic.py' file where we place all the logic of code, in this way we gain modularity and improve the way we have to perform the tests, doing these directly against code and not only with access to views. We have also been … -
Logging verbosity in django management commands
Django has a command line --verbosity 0/1/2/3 option, but it only has influence on some of django's internal output. It does not affect generic python logging levels. For management commands it can be handy to control the log level of the console output. First thing to look at, then is the logging setup. I normally have something like this in my settings.py: LOGGING = { ... 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, 'logfile': { 'level': 'INFO', 'class': 'logging.FileHandler', 'formatter': 'verbose', 'filename': os.path.join( SOMEWHERE, 'var', 'log', 'django.log'), }, }, 'loggers': { '': { 'handlers': ['console', 'logfile'], 'propagate': True, 'level': 'INFO', }, 'django.request': { 'handlers': ['console', 'logfile'], 'propagate': False, 'level': 'ERROR', # WARN also shows 404 errors }, ... some more specialised loggers ... } } A console handler that prints everything of log level DEBUG and higher and a logfile that starts at INFO (or WARN). Loggers: the '' one is the root logger. Everything that's not handled elsewhere ends up here. A level of INFO filters out all the DEBUG level messages. The django.request logger is one I normally configure separately as everything of level WARN and higher is normally logged to sentry. And I … -
Django 101 – Veri Tabani Tablolarinin Analizi (ER Diyagrami) #2
Video Icerisindekiler: – Projede kullanilacak ER tablosunun incelenmesi – Relations kavrami (Many To One · One To One · Many To Many) – Django Model dokumantasyonu -
Django 101 – Veri Tabani Tablolarinin Analizi (ER Diyagrami) #2
Video Icerisindekiler: – Projede kullanilacak ER tablosunun incelenmesi – Relations kavrami (Many To One · One To One · Many To Many) – Django Model dokumantasyonu