Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Django Tips #7: Function-Based Views vs Class-Based Views
An overview of the history and pros/cons of each approach. -
How to Use Django Bulk Inserts for Greater Efficiency
It's been awhile since we last discussed bulk inserts on the Caktus blog. The idea is simple: if you have an application that needs to insert a lot of data into a Django model — for example a background task that processes a CSV file (or some other text file) — it pays to "chunk" those updates to the database so that multiple records are created through a single database operation. This reduces the total number of round-trips to the database, something my colleague Dan Poirier discussed in more detail in the post linked above. Today, we use Django's Model.objects.bulk_create() regularly to help speed up operations that insert a lot of data into a database. One of those projects involves processing a spreadsheet with multiple tabs, each of which might contain thousands or even tens of thousands of records, some of which might correspond to multiple model classes. We also need to validate the data in the spreadsheet and return errors to the user as quickly as possible, so structuring the process efficiently helps to improve the overall user experience. While it's great to have support for bulk inserts directly in Django's ORM, the ORM does not provide much assistance … -
Customizing Django REST API Serializers
Adding extra fields to Serializers # serializers.py from rest_framework import serializers from test_app.models import Product class ProductSerializer(serializers.Serializer): product_id = serializers.IntegerField() product = serializers.SerializerMethodField('get_product_name') def get_product_name(self, obj): if obj.get("product_id"): obj_product = Product.objects.filter(id=obj.get("product_id")).first() if obj_product: return obj_product.name return None # API views.py from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from test_app.serializers import ProductsSerializer @api_view(['GET']) def list_products(request): response_data = {} response_data["data"] = ProductSerializer( [{"program": i} for i in [1, 2, 3]], many=True ).data return Response(response_data, status=status.HTTP_200_OK) Passing extra arguments to Serializer Class in Django Rest Framework Suppose we have searlizer called 'CollegeStudentsSerializer' which should return all students, branches details of a logged-in user college # serializers.py from rest_framework import serializers from test_app.models import Student, Branch class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ['id', 'first_name', 'last_name', 'branch'] class BranchSerializer(serializers.ModelSerializer): class Meta: model = Branch fields = ['id', 'name', 'code'] class CollegeDetailsSerializer(serializers.Serializer): students = serializers.SerializerMethodField('get_students') branches = serializers.SerializerMethodField('get_branches') def __init__(self, *args, **kwargs): context = kwargs.pop("context") self.college_id = context.get('college_id') super(CollegeDetailsSerializer, self).__init__(*args, **kwargs) def get_students(self, obj): return StudentSerializer( Student.objects.filter(college_id=self.college_id), many=True ).data def get_branches(self, obj): return BranchSerializer( Branch.objects.filter(college_id=self.college_id), many=True ).data # API views.py from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from test_app.serializers import CollegeDetailsSerializer @api_view(['GET']) def … -
7 Awesome Augmented Reality Solutions
Augmented reality, also known as AR, is increasingly everywhere. Businesses across industries are turning to augmented reality app development to help them create new ways to engage their customers. Educators are using AR to develop new ways of teaching, and medical professionals are using it to transform the way they approach treatment. People of all ages and backgrounds are trying out the built-in AR functionalities of their smartphones. The post 7 Awesome Augmented Reality Solutions appeared first on Distillery. -
Marginal Gain #1: Make Common Tasks Easy
Marginal gains are minor improvements that are relatively easy to make. A single marginal gain does not have a meaningful effect, but several can aggregate into significant progress. I first read about this concept in James Clear’s Atomic Habits, and was inspired to apply this philosophy to software development. For a better understanding of what … Continue reading Marginal Gain #1: Make Common Tasks Easy The post Marginal Gain #1: Make Common Tasks Easy appeared first on concise coder. -
Marginal Gain #1: Make Common Tasks Easy
Marginal gains are minor improvements that are relatively easy to make. A single marginal gain does not have a meaningful effect, but several can aggregate into significant progress. I first read about this concept in James Clear’s Atomic Habits, and was inspired to apply this philosophy to software development. For a better understanding of what … Continue reading Marginal Gain #1: Make Common Tasks Easy The post Marginal Gain #1: Make Common Tasks Easy appeared first on concise coder. -
Distillery Makes the Entrepreneur 360TM for the Second Year in a Row!
Achieving success in business is no easy task. Sustaining that success is even harder. That’s why we’re excited to share another milestone marking sustained success for Distillery. For the second year in a row, we’ve been honored on the Entrepreneur 360! The post Distillery Makes the Entrepreneur 360TM for the Second Year in a Row! appeared first on Distillery. -
How to Use Date Picker with Django
In this tutorial we are going to explore three date/datetime pickers options that you can easily use in a Django project. We are going to explore how to do it manually first, then how to set up a custom widget and finally how to use a third-party Django app with support to datetime pickers. Introduction Tempus Dominus Bootstrap 4 Direct Usage Custom Widget XDSoft DateTimePicker Direct Usage Custom Widget Fengyuan Chen’s Datepicker Direct Usage Custom Widget Conclusions Introduction The implementation of a date picker is mostly done on the front-end. The key part of the implementation is to assure Django will receive the date input value in the correct format, and also that Django will be able to reproduce the format when rendering a form with initial data. We can also use custom widgets to provide a deeper integration between the front-end and back-end and also to promote better reuse throughout a project. In the next sections we are going to explore following date pickers: Tempus Dominus Bootstrap 4 Docs Source XDSoft DateTimePicker Docs Source Fengyuan Chen’s Datepicker Docs Source Tempus Dominus Bootstrap 4 Docs Source This is a great JavaScript library and it integrate well with Bootstrap 4. The … -
Year in Review (2018)
An overview of 2018 and looking ahead to 2019. -
Into 2019!
A new year has come around and it's time to both look back at the old and onward to the future of Evennia, the Python MUD creation system! Last year Last year saw the release of Evennia 0.8. This version of Evennia changes some fundamental aspects of the server infrastructure so that the server can truly run in daemon mode as you would expect (no more running it in a GnuScreen session if you want to see logging to the terminal). It also adds the new Online Creation System, which lets builders create and define prototypes using a menu system as well as big improvements in the web client, such as multiple window-panes (allows the user to assign text to different windows to keep their client uncluttered) as well as plenty of fixes and features to help ease life for the Evennia developer. Thanks again to everyone who helped out and contributed to the release of Evennia 0.8!On a personal note, I spoke about Evennia at PyCon Sweden this December, which was fun. I might put up my talk and make a more detailed blog post about that in the future, but my talk got a surprising amount of attention and … -
Top 14 Pros of Using Django for Web Development
Django is one of the top frameworks for web development, but why is it so popular among developers and business owners? Let’s review the reasons why so many applications and features are being developed with Django. 1. Django is simple Django’s documentation is exemplary. It was initially launched with high-quality docs, and they are still maintained at the same level, which makes it easy to use. More than that, one of Django’s main purposes is to simplify the development process: it covers the basics, so you can focus on the more unique and/or complex features of your project. 2. Django works on Python The framework is based on Python — a high-level, dynamic, and interpreted programming language, well-loved by developers. Although it’s hard to find a language that can cover most programming tasks and problems, Python is a great choice for many of them. It’s one of the most popular languages of 2018, competing with C/++ and Java. Python is: Portable. Your code can be ported to many platforms, from PC and Linux to PlayStation. Multi-paradigm. It supports object-oriented programing, which is a simple way to code, as well as imperative programming. More interactive than most other languages. It resembles … -
How to Implement Grouped Model Choice Field
The Django forms API have two field types to work with multiple options: ChoiceField and ModelChoiceField. Both use select input as the default widget and they work in a similar way, except that ModelChoiceField is designed to handle QuerySets and work with foreign key relationships. A basic implementation using a ChoiceField would be: class ExpenseForm(forms.Form): CHOICES = ( (11, 'Credit Card'), (12, 'Student Loans'), (13, 'Taxes'), (21, 'Books'), (22, 'Games'), (31, 'Groceries'), (32, 'Restaurants'), ) amount = forms.DecimalField() date = forms.DateField() category = forms.ChoiceField(choices=CHOICES) Grouped Choice Field You can also organize the choices in groups to generate the <optgroup> tags like this: class ExpenseForm(forms.Form): CHOICES = ( ('Debt', ( (11, 'Credit Card'), (12, 'Student Loans'), (13, 'Taxes'), )), ('Entertainment', ( (21, 'Books'), (22, 'Games'), )), ('Everyday', ( (31, 'Groceries'), (32, 'Restaurants'), )), ) amount = forms.DecimalField() date = forms.DateField() category = forms.ChoiceField(choices=CHOICES) Grouped Model Choice Field When you are using a ModelChoiceField unfortunately there is no built-in solution. Recently I found a nice solution on Django’s ticket tracker, where someone proposed adding an opt_group argument to the ModelChoiceField. While the discussion is still ongoing, Simon Charette proposed a really good solution. Let’s see how we can integrate it in our … -
Caktus Blog: Top 18 Posts of 2018
In 2018, we published 44 posts on our blog, including technical how-to’s, a series on UX research methods, web development best practices, and tips for project management. Among all those posts, 18 rose to the top of the popularity list in 2018. Most Popular Posts of 2018 Creating Dynamic Forms with Django: Our most popular blog post delves into a straightforward approach to creating dynamic forms. Make ALL Your Django Forms Better: This post also focuses on Django forms. Learn how to efficiently build consistent forms, across an entire website. Django vs WordPress: How to decide?: Once you invest in a content management platform, the cost to switch later may be high. Learn about the differences between Django and WordPress, and see which one best fits your needs. Basics of Django Rest Framework: Django Rest Framework is a library which helps you build flexible APIs for your project. Learn how to use it, with this intro post. How to Fix your Python Code's Style: When you inherit code that doesn’t follow your style preferences, fix it quickly with the instructions in this post. Filtering and Pagination with Django: Learn to build a list page that allows filtering and pagination by … -
Your Application Shouldn’t Be Your CRM
If you’ve built applications, inevitably you’ve been tasked with building in complex CRM functionality. If you’ve built out e-comm platforms, you’ve definitely been given this requirement. Naturally, your next question is likely “so what counts as complex CRM functionality”? Complex CRM functionality includes any/all of the following: Triggering emails depending on a users’ in-app actionsTransitioning a user through a sales funnelUp and cross sells Our argument (and the point of this post) is the following: CRM logic belongs in a dedicated CRM. In other words, the application should be as clean of CRM behavior as possible, acting strictly as a bridge to the CRM and not as a CRM itself. In software, there are some common utterances thrown around the office fast-and-loose like. “DRY”, “KISS”, and “Don’t reinvent the wheel” are scribbled on PR reviews and commit comments, wrapping in their kitschiness a really powerful frame-of-mind: Don’t spend time on solved problems. It’s really easy remembering this lesson for the “hard” problems (example: you’re not building out a homegrown version of nltk or matplotlib), but too often we forget the same lesson is applicable to “easy” problems. While it’s easy to underestimate the functionality of a CRM, we’d be wise not to. Questions of deliverability, 3rd party email and … -
Django On Kubernetes – As Concisely As Possible
Django on Kubernetes When I search “django kubernetes”, it seems pretty straightforward what should come back. Worst case, there should be a lengthy blog post I can skim through to get to the sweet goodness that is sample config files. Best case, someone’s already filtered out the chaff and is throwing config files directly at my eyeballs. Lovely. Unfortunately, what I found fit one of two categories: Extremely detailed posts going into the nuts and bolts of Django, Kubernetes, cloud environments, and all that good stuff. Inexplicably, however, missing detail when it came to real-world examples.Guides for running Django on K8 for one specific cloud provider (looking at you GCP) So then what is this? This is definitely not extremely detailed. And it’s also definitely not cloud-specific. What this post contains is simply a rundown of some bare-bones config files, hopefully these can steer you clear of the time-pits which sucked me in. What it assumes is working familiarity with Kubernetes, Django, and Helm (https://helm.sh). Let’s get to it. A really stupid Django app And by really stupid, I mean just the output of django-admin.py startproject pizza Now, let’s dockerize this sucker. # Dockerfile FROM python:3.6.7-alpine3.7 RUN mkdir -p /code … -
How to Optimize Your Django REST Viewsets
The combination of Django and the Django REST framework is powerful. With just three classes (a model, a viewset, and a serializer), you can have a basic CRUD endpoint up and running. Although it is easy to get set up, it is also easy to end up with a view that makes hundreds of unnecessary database queries. As database queries are relatively slow, we want to avoid them as much as possible. In order to do this, we will follow Tip #4 from my Django ORM Optimization Tips post: 4. Use select_related() and prefetch_related() when you will need foreign-key/reverse related objects. Example The example we will be working with is based on a blog site. Here are the models: from django.db import models class BlogPost(models.Model): title = models.CharField(max_length=100) body = models.CharField(max_length=200) author = models.ForeignKey( 'User', on_delete=models.CASCADE, related_name='posts') def __str__(self): return '{} - {}'.format(self.author.name, self.title) class User(models.Model): username = models.CharField(max_length=100) name = models.CharField(max_length=100) def __str__(self): return '{} - {}'.format(self.username, self.name) class Comment(models.Model): author = models.ForeignKey( 'User', on_delete=models.CASCADE, related_name='comments') comment = models.CharField(max_length=200) post = models.ForeignKey( 'BlogPost', on_delete=models.CASCADE, related_name='comments') def __str__(self): return '{} - {}'.format(self.post, self.comment) Here are the serializers: from rest_framework import serializers from .models import BlogPost, Comment, User class UserSerializer(serializers.ModelSerializer): class Meta: model = … -
How to Optimize Your Django REST Viewsets
The combination of Django and the Django REST framework is powerful. With just three classes (a model, a viewset, and a serializer), you can have a basic CRUD endpoint up and running. Although it is easy to get set up, it is also easy to end up with a view that makes hundreds of unnecessary database queries. As database queries are relatively slow, we want to avoid them as much as possible. The post How to Optimize Your Django REST Viewsets appeared first on concise coder. -
Django Quiz 2018
On Monday evening I gave a quiz at the December London Django Meetup Group for the third year running - that makes it a tradition! Here it is so you can follow it at home - answers are at the bottom, no cheating. Enjoy! Part 1: Trivia 1. What does DSF stand for? Django Sans Forms Django Server Forgery Django Software Foundation Database Sequence File 2. Which two of the following are Django fellows? One point each. Django Freeman Grace Hopper Carlton Gibson Donald Knuth Rick Sanchez Tim Graham 3. Which City was Djangocon 2018 (US) in? 4. Which City was Djangocon EU 2018 in? One point for city, one point for country. 5. Name the official Django mailing lists One point each. Part 2: Coding in Django 6. What does CSRF stand for? Cross Side Request Forms Cranky Server Rack Fire Crispy Sizzly Relished Forms Cross Site Request Forgery 7. What does ORM stand for? Online Realtime Magic Object-Relational Mapper Objection Relationship Manager Ouch Random Methods 8. What does CBV stand for? Classist Biased Views Classy Blinged View Class Based View Classic Basic View 9. Which of these is true about CommonMiddleware? It was deprecated and will be removed … -
Distillery’s 2018 Year in Review
The end of the year is often a time for celebrations. For Distillery, the end of 2018 is absolutely worth celebrating: It marks 10 years since we’ve been in business! The post Distillery’s 2018 Year in Review appeared first on Distillery. -
What's New in the Third Edition of Web Development with Django Cookbook?
A couple of months ago the third release of Django Cookbook was published under the title Django 2 Web Development Cookbook - Third Edition. This edition was thoroughly and progressively re-written by Jake Kronika, the guy who had reviewed my second edition and had added a lot of value to it. I was sure that he wouldn't disappoint the readers, so I invited him to write the update. In this article, I will guide you through the main new highlights of over 500 pages of this new book. Up to Date Just like William S. Vincent's books, Django 2 Web Development Cookbook - Third Edition is adapted to Django 2.1 and Python 3.6. So you will be dealing with the state of the art technologies building your Django projects. Unicode strings, f-strings, super() without parameters, HTML5 tags, and object-oriented JavaScript to mention a few are used all over the book. The code is carefully generalized and even more adapted to the Don't-Repeat-Yourself (DRY) principle. Working with Docker Docker is one of the most popular deployment technologies and Jake gives a good compact introduction how to use it with Django. Using Environment Variables for Configuration 12-factor app guidelines suggest saving app … -
How to Use JWT Authentication with Django REST Framework
JWT stand for JSON Web Token and it is an authentication strategy used by client/server applications where the client is a Web application using JavaScript and some frontend framework like Angular, React or VueJS. In this tutorial we are going to explore the specifics of JWT authentication. If you want to learn more about Token-based authentication using Django REST Framework (DRF), or if you want to know how to start a new DRF project you can read this tutorial: How to Implement Token Authentication using Django REST Framework. The concepts are the same, we are just going to switch the authentication backend. How JWT Works? Installation & Setup Example Code Usage Obtain Token Refresh Token What’s The Point of The Refresh Token? Further Reading How JWT Works? The JWT is just an authorization token that should be included in all requests: curl http://127.0.0.1:8000/hello/ -H 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTQzODI4NDMxLCJqdGkiOiI3ZjU5OTdiNzE1MGQ0NjU3OWRjMmI0OTE2NzA5N2U3YiIsInVzZXJfaWQiOjF9.Ju70kdcaHKn1Qaz8H42zrOYk0Jx9kIckTn9Xx7vhikY' The JWT is acquired by exchanging an username + password for an access token and an refresh token. The access token is usually short-lived (expires in 5 min or so, can be customized though). The refresh token lives a little bit longer (expires in 24 hours, also customizable). It is comparable to an … -
What's New in the Third Edition of Web Development with Django Cookbook?
A couple of months ago the third release of Django Cookbook was published under the title Django 2 Web Development Cookbook - Third Edition. This edition was thoroughly and progressively re-written by Jake Kronika, the guy who had reviewed my second edition and had added a lot of value to it. I was sure that he wouldn't disappoint the readers, so I invited him to write the update. In this article, I will guide you through the main new highlights of over 500 pages of this new book. Up to Date Just like William S. Vincent's books, Django 2 Web Development Cookbook - Third Edition is adapted to Django 2.1 and Python 3.6. So you will be dealing with the state of the art technologies building your Django projects. Unicode strings, f-strings, super() without parameters, HTML5 tags, and object-oriented JavaScript to mention a few are used all over the book. The code is carefully generalized and even more adapted to the Don't-Repeat-Yourself (DRY) principle. Working with Docker Docker is one of the most popular deployment technologies and Jake gives a good compact introduction how to use it with Django. Using Environment Variables for Configuration 12-factor app guidelines suggest saving app … -
Python and Django Logging in Plain English
If you’ve ever written a program and printed out a value to see what’s going on during execution, then you understand at some level why logging is so valuable. Knowing what’s happening in your code at a point in time is enormously useful from both technical and business perspectives. This knowledge lets developers and product managers make smart choices about what systems to fix or modify and lets them see what actions users take when they use your software.Thankfully, Python has a much more powerful, built-in library for logging than the print() function, and it’s named, simply enough, logging. The library is flexible and customizable but has a reputation for being hard to understand at first because there are multiple moving pieces. Django uses this library by default and makes it easy to integrate into your project.So while this is technically an article about logging with Django, the best way to explore that topic is to understand the logging library in general, and how Django uses it specifically. This is part two of a four-part series about what happens when the setup function in __init__.py gets executed.How Django accesses project settings.How Django and Python manage logging. Why Django allows the … -
Django 2 Ajax CRUD with Python 3.7 and jQuery
In this tutorial, you'll learn how to send Ajax requests in Django 2 and Python 3.7 to add CRUD operations in your application and manipulate your Django models and database without having to refresh your web pages each time. Ajax stands for Asynchronous JavaScript and XML and it's a way for getting data from the server and updating the page on the fly without refreshing the page. Creating a Virtual Environment Make sure you have Python 3 installed (Python 3.7 is the latest as of this writing) and start by creating a virtual environment for your project's packages: $ python -m venv myenv Next, activate your virtual environment using: $ source myenv/bin/activate Installing Django 2 and Creating a Project Now, you need to install Django using pip: $ python -m pip install django Next, create a Django project using: $ django-admin startproject djangoajaxdemo Next you need to create a Django application using the manage.py script: $ cd djangoajaxdemo $ python manage.py startapp rooms Next you need to add it to your project's installed apps array in the settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rooms' ] Adding jQuery In this tutorial, we'll be using jQuery to … -
Python Overtakes Java
It's fitting that the first bl...