Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
An easy tip to quickly access the Python reference
If you are like me, you visit the Python Standard Library Reference all the time. You already know there’s a “datetime” module, a “random” module, an “os.path” module, and so on, so how do you quickly go there to read the reference? Here’s what I do. I switch to my browser with Alt+Tab, I key in Ctrl+L or Ctrl+T, in the URL tab I type “p3 datetime”, and I press Enter. The whole procedure takes less than 3 seconds, and it immediately takes me to the Python 3 reference for datetime. How to do it Firefox: Visit https://docs.python.org/3/library/datetime.html and bookmark it. Go to the properties of the new bookmark, change the name to “Python 3 Library Reference”, specify “p3” in the keyword field, and in the URL change the “datetime” part to “%s”, so that the whole URL is https://docs.python.org/3/library/%s.html. Other browsers: I don’t know, but the information is around (e.g. Chrome) Actually I have a copy of the documentation on my local machine, so the URL I’m actually using is file:///usr/share/doc/python3-doc/html/library/%s.html. I have such shortcuts for the Python 3 library, the Python 2 library, the Django settings (but the setting must be typed in lower case and with hyphens … -
Django 1.11 Highlights
You can't always, easily, keep up with the latest and greatest of what is coming out in django, so since we have a new release candidate for django 1.11 here are a few of the highlights. I would say there are some interesting things that are on the horizon for django, especially since this is the last 1.x release before we are on to 2.0. Django 1.11 Highlights -
Come Visit Us at PyCon 2017
PyCon 2017 is fast approaching, and we’re excited to support the event this year as sponsors once again. It’s a great opportunity to meet new friends, exchange ideas and interact with the community at large. Caktus has attended PyCon since 2010 and our developers are always excited to learn from the variety of talks scheduled for the conference. We’ll be represented by a team of 10 attendees who can’t wait to get to Portland. We look forward to welcoming visitors to our booth from May 18-20 to chat about building Django apps, Python best practices, or industry trends. Interested in working with Caktus or speaking with us about what it’s like to work here? Stop by during the job fair to learn more about joining Caktus as a Django Web Developer. And of course, we’ll be doing giveaways - but you’ll have to stop by and say hi to win! In the meantime, follow Caktus on Twitter for a sneak preview of our giveaways and an early chance to win (more on this soon, so keep an eye on our feed). Our booth is always busy, so be sure to contact us in advance to ensure dedicated time with our … -
Django ile Web Programlama Video Serisi
Toplam 41 video dan oluşan Django ile Web Programlama eğitim serisi, temel düzeyde Python bilgisi olanlar ve daha önceden web programlama bilgisine sahip olmayanlar için temel seviyeden başlayıp, adım adım giderek Django ile bir web sitesi oluşturmayı hedefler. Django’nun temel mantığını anladıktan sonra, ortalama bir websitesini geliştirmek vaktinizi çok fazla almayacaktır. Django Nedir? Django, tamamen... Django ile Web Programlama Video Serisi yazısı ilk önce Python Türkiye üzerinde ortaya çıktı. -
Django ile Web Programlama Video Serisi
Toplam 41 video dan oluşan Django ile Web Programlama eğitim serisi, temel düzeyde Python bilgisi olanlar ve daha önceden web programlama bilgisine sahip olmayanlar için temel seviyeden başlayıp, adım adım giderek Django ile bir web sitesi oluşturmayı hedefler. Django’nun temel mantığını anladıktan sonra, ortalama bir websitesini geliştirmek vaktinizi çok fazla almayacaktır. Django Nedir? Django, tamamen Python Diliyle yazılmış, ücretsiz ve açık kaynak bir web çatısıdır. Web Çatısı, ingilizce adıyla Web Framework, websitesi geliştirmeyi hızlandıran ve kolaylaştıran bir yapıdır. Neden Django? Django’nun en önemli özelliği, hızlı geliştirme sürecidir. Detaylarla uğraşmadan az kodla çok iş yaparak, sadece ulaşmak istediğiniz şeye odaklanırsınız. Django MVC’ye çok benzer olan MVT yapısını kullanır. MVT (Model View Template) demektir. Bu kavramları kısaca açıklamak gerekirse Model katmanı, veri türlerini ve veritabanı nesnelerini tanımladığımız yerdir. View katmanı Python dilini kullanarak yazacağımız, arka planda çalışan fonksiyonlar veya methodlar bölümüdür. Template katmanı ise daha akıllı ve dinamik olarak yazıcağımız html sayfalarıdır. Django Teknolojisi Kullanan Popüler Websiteleri : Instagram, National Geographic, NASA, Pinterest, Disqus, The Guardian, Bit Bucket, Eventbrite Daha fazlası için videoları inceleyebilirsiniz. Videolar YouTube’da ücretsiz olarak yayımlanmaktadır. Faydalı olması dileğiyle.. -
Django REST Framework: Using the request object
While working with Django REST Framework aka DRF, we often wonder how to customize our response based on request parameters. May be we want to check something against the logged in user (request.user) ? Or may be we want to modify part of our response based on a certain request parameter? How do we do that? We will discuss a few use cases below. ModelViewSet - Filtering based on request This is very often required while using ModelViewSets. We have many Items in our database. But when listing them, we only want to display the items belonging to the current logged in user. from rest_framework.permissions import IsAuthenticated class ItemViewSet(ModelViewSet): permission_classes = (IsAuthenticated,) serializer_class = ItemSerializer def get_queryset(self): queryset = Item.objects.all().filter(user=request.user) another_param = self.request.GET.get('another_param') if another_param: queryset = queryset.filter(another_field=another_param) return queryset If you are using the awesome ModelViewSet, you can override the get_queryset method. Inside it, you can access the request object as self.request. In the above example, we are only listing the items which has our current user set as their user field. At the same time, we are also filtering the queryset based on another parameter. Basically you have the queryset and self.request available to you, feel free to … -
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. We were first introduced to Elastic Beanstalk when taking over an existing project that used it. It's not without its shortcomings, but we've generally been happy enough with it to stick with it for the project and consider it for others. Basics Elastic Beanstalk can handle a number of technologies that people use to build web sites, including Python (2.7 and 3.4), Java, PHP, .Net, Node.js, and Ruby. More are probably in the works. You can also deploy containers, with whatever you want in them. To add a site to Elastic Beanstalk, you create a new Elastic Beanstalk application, set some configuration, and upload the source for your application. Then Elastic Beanstalk will provision the necessary underlying resources, such as EC2 (virtual machine) instances, load balancers, autoscaling groups, DNS, etc, and install your application appropriately. Elastic Beanstalk can monitor the load and automatically scale underlying resources as needed. When your application needs updating, you upload the updated source, and Elastic Beanstalk updates the … -
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? -
A Production-ready Dockerfile for Your Python/Django App
Docker has matured a lot since it was released nearly 4 years ago. We’ve been watching it closely at Caktus, and have been thrilled by the adoption -- both by the community and by service providers. As a team of Python and Django developers, we’re always searching for best of breed deployment tools. Docker is a clear fit for packaging the underlying code for many projects, including the Python and Django apps we build at Caktus. Technical overview There are many ways to containerize a Python/Django app, no one of which could be considered “the best.” That being said, I think the following approach provides a good balance of simplicity, configurability, and container size. The specific tools I’ll be using are: Docker (of course), Alpine Linux, and uWSGI. Alpine Linux is a simple, lightweight Linux distribution based on musl libc and Busybox. Its main claim to fame on the container landscape is that it can create a very small (5MB) Docker image. Typically one’s application will be much larger than that after the code and all dependencies have been included, but the container will still be much smaller than if based on a general-purpose Linux distribution. There are many WSGI … -
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...