Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Django CRUD: Python 3.7 & Generic Class-Based Views
Throughout this tutorial, you'll create a Django CRUD example application using generic class based views. You will be using the latest Python 3.7 version. You'll learn to quickly create CRUD views by using the Django built-in generic views such as ListView, DetailView, CreateView, UpdateView and DeleteView. CRUD stands for create, read, update and delete and it simply refers to a set of common operations that are used in most web applications to interact with data from a database. It basically provides a CRUD interface that allows your users to create, read, update and delete data in your application database like MySQL, PostgreSQL or Oracle etc. Prerequisites You'll need to have the following prerequisites: A development machine with Python 3.7, pip and venv installed, A basic knowledge of Python, A working knowledge of Django. In this tutorial, you'll learn about: Django class based views, Creating and activating a virtual environment using venv, Installing Django using pip and creating a new project using django-admin.py, Creating a new Django application using manage.py, Creating a Django ORM model, Enabling the admin Interface, Creating the class based views, Creating the templates, Adding the URLs. Creating and Activating a Virtual Environment When working with new Python … -
How to implement TokenBasedAuthentication in DjangoRestFramework?
If you are new to Django REST framework, then you can go through below blog posts to understand how to develop RESTful API with Django REST framework. How to develop RESTful webservice in Django using Django REST framework Introduction to API development with Django REST framework Generic, Functional based and Class based views in Django REST Framework REST framework provides a number of authentication methods and also allows us to implement custom methods. This blog shows you how to use Token Authentication to authenticate users within a Django Application. Token Authentication is a way to authorize users by using an Auth Token. First, you have to add 'rest_framework.authtoken' to your INSTALLED_APPS setting as Token Authentication uses a special model called Token, which is used to store your user authentication tokens. INSTALLED_APPS = ( ... 'rest_framework', 'rest_framework.authtoken' ) Then you must configure the authentication scheme to include 'TokenAuthentication' using the 'DEFAULT_AUTHENTICATION_CLASSES' setting like below REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } Now you must run 'python manage.py migrate' after adding above settings to update the database with new Token model. You can create tokens for existing users like below from rest_framework.authtoken.models import Token token = Token.objects.create(user=) … -
Talk Python Podcast Interview - Teaching Django
An interview with Michael Kennedy on learning and teaching Django. -
Distillery Developer Is a Driving Force in Building Kodi’s Open Source Software
Think about the last time you were frustrated by a computer software problem. Now, imagine that you could simply elect to fix the problem yourself. Back in 2014, that’s exactly what happened to Distillery Full Stack Developer Anton Fedchin (afedchin). The post Distillery Developer Is a Driving Force in Building Kodi’s Open Source Software appeared first on Distillery. -
Is Django a Full Stack Framework?
Clearing up common confusion on front-end vs back-end. -
Django Tips & Tricks #11 - Finding High-impact Performance Bottlenecks
Introduction When optimizing performance of web application, a common mistake is to start with optimizing the slowest page(or API). In addition to considering response time, we should also consider the traffic it is receving to priorotize the order of optimization. In this article we will profile a django webapp, find high-impact performance bottlenecks and then start optimization them to yield better performance. Profiling django-silk is an open source profiling tool which intercepts and stores HTTP requests data. Install it with pip. pip install django-silk Add silk to installed apps and include silk middleware in django settings. MIDDLEWARE = [ ... 'silk.middleware.SilkyMiddleware', ... ] INSTALLED_APPS = ( ... 'silk' ) Run migrations so that Silk can create required database tables to store profile data. $ python manage.py makemigrations $ python manage.py migrate $ python manage.py collectstatic Include silk urls in root urlconf to view the profile data. urlpatterns += [url(r'^silk/', include('silk.urls', namespace='silk'))] On silk requests page(http://host/silk/requests/), we can see all requests and sort them by overall time or time spent in database. High Impact Bottlenecks Silk creates silk_request table which contains information about the requests processed by django. $ pgcli library> \d silk_request; +--------------------+--------------------------+-------------+ | Column | Type | Modifiers | … -
Find High-impact Performance Bottlenecks in Django
Introduction When optimizing performance of web application, a common mistake is to start with optimizing the slowest page(or API). In addition to considering response time, we should also consider the traffic it is receving to priorotize the order of optimization. In this article we will profile a django webapp, find high-impact performance bottlenecks and then start optimization them to yield better performance. Profiling django-silk is an open source profiling tool which intercepts and stores HTTP requests data. Install it with pip. pip install django-silk Add silk to installed apps and include silk middleware in django settings. MIDDLEWARE = [ ... 'silk.middleware.SilkyMiddleware', ... ] INSTALLED_APPS = ( ... 'silk' ) Run migrations so that Silk can create required database tables to store profile data. $ python manage.py makemigrations $ python manage.py migrate $ python manage.py collectstatic Include silk urls in root urlconf to view the profile data. urlpatterns += [url(r'^silk/', include('silk.urls', namespace='silk'))] On silk requests page(http://host/silk/requests/), we can see all requests and sort them by overall time or time spent in database. High Impact Bottlenecks Silk creates silk_request table which contains information about the requests processed by django. $ pgcli library> \d silk_request; +--------------------+--------------------------+-------------+ | Column | Type | Modifiers | … -
Django 'Hello, World' with Docker
How to start a new project with Django and Docker. -
Django Authentication — Login, Register, Logout and Password Reset
In this tutorial, you'll learn how to easily add a complete authentication system to your Django application with login, logout and password change and reset functionalities. We'll also be using django-crispy-forms and Bootstrap 4 for styling the application UI. Prerequisites Let's start with the prerequisites for this tutorial. In order to follow the tutorial step by step, you'll need a few requirements, such as: Basic knowledge of Python, Working knowledge of Django (django-admin.py and manage.py), A recent version of Python 3 installed on your system (the latest version is 3.7) We will be using pip and venv which are bundled as modules in recent versions of Python so you don't actually need to install them unless you are working with old versions. If you are ready, lets go started! Creating a Virtual Environment A virtual environment allows you to isolate your current project dependencies from the rest of packages installed globally on your system or in the other virtual environments. You can either use virtualenv which needs to be installed on your system or the venv module available as a module in recent versions of Python 3. Go to your command terminal and run: $ python -m venv env Next, … -
Understanding middleware functionality in django2.0
Middlewares are used to modify the request object which is sent to the view or to modify the response object returned from the view. They allow us to modify request/response globally. Django's old-style middleware: Prior to Django 1.10, there were 5 hooks. Any class that implements process_request(), process_view(), process_exception(), process_template_response() and process_response() methods can act as a middleware and all of these are specified in the setting MIDDLEWARE_CLASSES. The first two methods - process_request(), process_view() are executed before the execution of the view. The next three methods, process_exception(), process_template_response() and process_response() are executed after view returns the response object. Django's new-style middleware: The most important change you need to do when upgrading to Django 2.0 is to change MIDDLEWARE_CLASSES to MIDDLEWARE in settings.py file. In django 2.0 support for old-style middleware using settings.MIDDLEWARE_CLASSES is removed. The old middleware must be a class where as the new middleware is any callable, which takes a get_response callable and returns a callable that takes the request and returns a response. These middlewares should be specified in MIDDLEWARE setting. class TimeStampMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): request.timestamp = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') response = self.get_response(request) return response Note: Here the get_response can … -
Django Form Example—Bootstrap 4 UI via django-crispy-forms
In this practical tutorial, you will build a simple example Django application with a form styled with Bootstrap 4. In this tutorial, you'll be using django-crispy-forms, a popular package that makes it easy for Django developers to create beautiful forms easily and without re-inventing the wheel. In this tutorial, you'll also be using Bootstrap 4—the latest version of the most popular CSS and HTML framework for building HTML interfaces—to style the form. The django-crispy-forms enables you to quickly add and render Bootstrap 4 styled forms with a few lines of code. Prerequisites You need to have these requirements if you want to create the example in this tutorial, step by step in your machine: A recent version of Python 3 (3.7 is the latest), A basic knowledge of Python, A working knowledge of Django. Creating a Virtual Environment & Installing Django First, begin by creating a virtual environment for your project using the venv module: $ python -m venv env Next, activate your environment using source: $ source env/bin/activate Next, install django in your virtual environment using pip: $ python -m pip install django Creating a Django Project & Application After installing Django, you need to create a project using … -
Why Successful Companies Like Google Outsource: 5 Use Cases You Can Learn From
What do many of the world’s most successful businesses have in common? They outsource some of their work. As companies like Google, Slack, Microsoft, Alibaba, and GitHub have long known, outsourcing can deliver manifold benefits to businesses. These benefits include money saved, time saved, staffing flexibility, speed to innovation, increased control over internal resources, and increased access to top talent, among other compelling benefits. The post Why Successful Companies Like Google Outsource: 5 Use Cases You Can Learn From appeared first on Distillery. -
Django TemplateView Example — URLs, GET and as_view
Django Templates are used to create HTML interfaces that get rendered with a Django view. A TemplateView is a generic class-based view that helps developers create a view for a specific template without re-inventing the wheel. TemplateView is the simplest one of many generic views provided by Django. You can create a view for an example index.html template by simply sub-classing TemplateView and providing the template name via a template_name variable. TemplateView is more convenient when you need to create views that display static HTML pages without context or forms that respond to GET requests. TemplateView is simply a sub-class of the View class with some repetitive and boilerplate code that renders a Django template and sends it to the client. Django View Example Before looking at how to use TemplateView, let's first look at how we can create a Django view from scratch. Let's pretend we need to create a home view. This is the required code that you need to write in the views.py file of your application from django.shortcuts import render from django.views.generic.base import View class Home(View): def get(self, request, *args, **kwargs): return render(request, "index.html") If our app is named myapp, you need to create a templates/myapp … -
CSS Grid Layout Tutorial—Styling a Django Template
Throughout this tutorial, we'll learn about CSS Grid Layout. We'll be using a Django template. There are many popular techniques for creating responsive layouts. In this tutorial, we'll be building a simple Django web application with a modern UI styled with CSS Grid layout. By building the UI using CSS Grid, you'll learn about many useful and easy techniques for achieving popular requirements such as centering and spanning items, switching layouts depending on the screen size and creating responsive UIs. Before, we dive into practical steps, let's first introduce CSS Grid. What is CSS Grid? CSS Grid is a modern 2-dimentionnal system for creating HTML layouts. It's now supported by most web browsers. It makes creating professional and complex layouts more easier than ever! CSS Grid Layout allows you to build advanced grid layouts in CSS instead of HTML like the case for tables for example. Unlike CSS floats and HTML tables you can create a grid layout in a straightforward way. You simply need to use an HTML element with its display property set to grid or inline-grid. This way, any elements contained in the parent element or the container becomes grid items. If you don't specify any other … -
Write drunk, test automated: documentation quality assurance - Sven Strack
This is my summary of the write the docs meetup in Amsterdam at the Adyen office, november 2018. Sven's experience is mostly in open source projects (mainly Plone, a python CMS). He's also involved in https://testthedocs.org and https://rakpart.testthedocs.org, a collection of tools for documentation tests. He has some disclaimers beforehand: There is no perfect setup. Automated checks can only help up to a certain level. Getting a CI (continuous integration) setup working is often tricky. Before you start testing your documentation, you'll need some insight. Start with getting an overview of your documentation. Who is committing to it? Which parts are there? Which parts of the documentation are updated most often? Are the committers native speakers yes/no? Which part of the documentation has the most bug reports. So: gather statistics. Also: try to figure out who reads your documentation. Where do they come from? What are the search terms they use to find your documentation in google? You can use these statistics to focus your development effort. Important: planning. If your documentation in English, plan beforehand if you want it to be in UK or US English. Define style guides. If you have automatic checks, define standards beforehand: do you … -
Django Function-Based Views vs. Class-Based Views
Django views are an essential part of most Django applications. They carry out user requests to perform actions and return different types of data. Django provides two distinct methods for creating a view: function-based and class-based. Many discussions have been had over the benefits of using one over the other. I believe that the benefits of using one or the other is highly circumstantial. In this post, I will outline the guidelines I use to determine which option is better for different circumstances. Function-Based Views (FBVs) What are they? You are probably familiar with function-based views. They are generally the first type of view a beginner learns about (and in some cases, the only one). FBVs are basically just functions that take a request argument. from django.http import HttpResponse import datetime def current_datetime(request): now = datetime.datetime.now() html = "<html><body>It is now %s.</body></html>" % now return HttpResponse(html) FBVs are simple to write and understand. Unlike class-based views, the logic is sequential and explicit. There is no need to think about hidden functionality. When should they be used? In my opinion, FBVs should be used minimally. If you are going to use them, only use them for really short and simple views. … -
Django Function-Based Views vs. Class-Based Views
Django views are an essential part of most Django applications. They carry out user requests to perform actions and return different types of data. Django provides two distinct methods for creating a view: function-based and class-based. Many discussions have been had over the benefits of using one over the other. I believe that the benefits … Continue reading Django Function-Based Views vs. Class-Based Views The post Django Function-Based Views vs. Class-Based Views appeared first on concise coder. -
My interview kickoff script, annotated
When I interview, I say nearly the same thing at the beginning of the interview. It’s a script I’ve practiced and honed over the years . It’s only eleven sentences, but each has a specific purposes. I’ve iterated on this for years, and it’s pretty tightly honed at this point. I published this script in the guide to interviewing I wrote at 18F last year, but never got a chance to break down where it comes from -
Amsterdam Python meetup, november 2018
My summary of the 28 november python meetup at the Byte office. I myself also gave a talk (about cookiecutter) but I obviously haven't made a summary of that. I'll try to summarize that one later :-) Project Auger - Chris Laffra One of Chris' pet projects is auger, automated unittest generation. He wrote it when lying in bed with a broken ankle and thought about what he hated most: writing tests. Auger? Automated Unittest GEneRator. It works by running a tracer The project's idea is: Write code as always Don't worry about tests Run the auger tracer to record function parameter values and function results. After recording, you can generate mocks and assertions. "But this breaks test driven development"!!! Actually, not quite. It can be useful if you have to start working on an existing code base without any tests: you can generate a basic set of tests to start from. So: it records what you did once and uses that as a starting point for your tests. It makes sure that what ones worked keeps on working. It works with a "context manager". A context manager normally has __enter__() and __exit__(). But you can add more interesting things. … -
Python Application Dependency Management in 2018
We have more ways to manage dependencies in Python applications than ever. But how do they fare in production? Unfortunately this topic turned out to be quite polarizing and was at the center of a lot of heated debates. This is my attempt at an opinionated review through a DevOps lens. -
Advanced Form Rendering with Django Crispy Forms
[Django 2.1.3 / Python 3.6.5 / Bootstrap 4.1.3] In this tutorial we are going to explore some of the Django Crispy Forms features to handle advanced/custom forms rendering. This blog post started as a discussion in our community forum, so I decided to compile the insights and solutions in a blog post to benefit a wider audience. Table of Contents Introduction Basic Form Rendering Basic Crispy Form Rendering Custom Fields Placement with Crispy Forms Crispy Forms Layout Helpers Custom Crispy Field Conclusions Introduction Throughout this tutorial we are going to implement the following Bootstrap 4 form using Django APIs: This was taken from Bootstrap 4 official documentation as an example of how to use form rows. NOTE! The examples below refer to a base.html template. Consider the code below: base.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> </head> <body> <div class="container"> {% block content %} {% endblock %} </div> </body> </html> If you don’t know how to install django-crispy-forms, please follow the instructions here first: How to Use Bootstrap 4 Forms With Django Basic Form Rendering The Python code required to represent the form above is the following: from django … -
Hire me to help you hire
Do you have a growing engineering organization that needs help hiring effectively? I can help! I have consulting availability over the next few months to help organizations hire better. I can design your hiring process, write interview questions, teach staff how to interview successfully, or even run your hiring rounds. Read on more for details, or if you’re interested, hit me up: jacob@revsys.com. What I can do for you In a nutshell: I will help you hire more effectively. -
A Cure for Cold Feet: Why It’s Time to Open the Door to Outsourcing
Flexibility that speeds innovation while reducing your risk. Access to top talent, regardless of location or long-term interest. Fit-for-purpose teams that exist for only as long as you need them. Increased control over how your internal resources are used. Money saved across the board on benefits, training, office space, turnover, and downtime. Processes and protocols customized to ensure quality, efficiency, consistency, continuity, transparency, responsiveness, solid results, and fast answers. Increased time to focus on running your business and executing against your strategic imperatives. The post A Cure for Cold Feet: Why It’s Time to Open the Door to Outsourcing appeared first on Distillery. -
Truths programmers should know about case
A couple weeks ago I gave a talk about usernames at North Bay Python. The content came mostly from things I’ve learned in roughly 12 years of maintaining django-registration, which has taught me more than I ever wanted to know about how complex even “simple” things can be. I mentioned toward the beginning of the talk, though, that it wasn’t going to be one of those “falsehoods programmers believe about X” things. If you’re not ... Read full entry -
Keyset Pagination in Django
Pagination is great. Nothing worse than having an HTML page that renders 25000 rows in a table. Django Pagination is also great. It makes it super easy to declare that a view (that inherits from `MultipleObjectMixin`) should paginate its results: {% highlight python %} class List(ListView): queryset = Foo.objects.order_by('bar', '-baz') paginate_by = 10 template_name = 'foo.html' {% endhighlight %} Django pagination uses the LIMIT/OFFSET method. This is fine for smaller offsets, but once you start getting beyond a few pages, it can perform really badly. This is because the database needs to fetch all of the previous rows, even though it discards them. Using Keyset Pagination allows for better performing "next page" fetches, at the cost of not being able to randomly fetch a page. That is, if you know the last element from page N-1, then you may fetch page N, but otherwise you really can't. Keyset Pagination, sometimes called the Seek Method, has been documented by [Markus Winand](https://use-the-index-luke.com/sql/partial-results/fetch-next-page) and [Joe Nelson](https://www.citusdata.com/blog/2016/03/30/five-ways-to-paginate/). If you are not familiar with the concept, I strongly suggest you read the articles above. Django's pagination is somewhat pluggable: you may switch out the paginator in a Django ListView, for instance, allowing you to do …