Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
How to Customize Django Admin Application
Django Admin interface or app is a powerful feature of Django framework as it allows you to automatically scaffold a full featured CRUD application for your database models saving you from reinventing the wheel when building admin interfaces or back offices for your projects .It can also be used for building quick prototypes . Most developers are not aware of the hidden power of Django admin so in this tutorial we are going to show you how we can extend it to customize its look and also its behavior with custom actions . The Admin site is enabled by default in each generated Django project . To create an admin site or back office you need to follow these predefined steps : First create your database models in models.py Next register your models with Django Admin in admin.py module . Customize the admin area with optional look or custom actions and views . Lets use the models from a simple product inventory manager where we have 4 models : Product ,Family , Location and Transaction . After creating a skeleton project with django-admin.py utility .You'll have Django admin already included and configured for you all you have to do is … -
Getting started with Django Rest Framework by Building a Simple Product Inventory Manager
Django offers developers many packages/frameworks to build web Rest APIs ,among them Django Rest Framework or DRF which is by far the most popular and powerful Rest API Framework . In this tutorial we will see how to use DRF to create a Rest API for a simple products inventory manager with 4 models . Getting started Lets start by following these steps : Create a virtual environement . Install both Django and Django Rest Framework . Create A Django project . Create a Django app . Add database models in inventory/models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models class Product(models.Model): sku = models.CharField(max_length=13,help_text="Enter Product Stock Keeping Unit") barcode = models.CharField(max_length=13,help_text="Enter Product Barcode (ISBN, UPC ...)") title = models.CharField(max_length=200, help_text="Enter Product Title") description = models.TextField(help_text="Enter Product Description") unitCost = models.FloatField(help_text="Enter Product Unit Cost") unit = models.CharField(max_length=10,help_text="Enter Product Unit ") quantity = models.FloatField(help_text="Enter Product Quantity") minQuantity = models.FloatField(help_text="Enter Product Min Quantity") family = models.ForeignKey('Family') location = models.ForeignKey('Location') def get_absolute_url(self): """ Returns the url to access a particular instance of Product. """ return reverse('product-detail-view', args=[str(self.id)]) def __str__(self): return self.title class Family(models.Model): reference = models.CharField(max_length=13, help_text="Enter Family Reference") title = models.CharField(max_length=200, help_text="Enter Family Title") description = models.TextField(help_text="Enter … -
How to Customize Django Admin Application
Django Admin interface or app is a powerful feature of Django framework as it allows you to automatically scaffold a full featured CRUD application for your database models saving you from reinventing the wheel when building admin interfaces or back offices for your projects .It can also be used for building quick prototypes . Most developers are not aware of the hidden power of Django admin so in this tutorial we are going to show you how we can extend it to customize its look and also its behavior with custom actions . The Admin site is enabled by default in each generated Django project . To create an admin site or back office you need to follow these predefined steps : First create your database models in models.py Next register your models with Django Admin in admin.py module . Customize the admin area with optional look or custom actions and views . Lets use the models from a simple product inventory manager where we have 4 models : Product ,Family , Location and Transaction . After creating a skeleton project with django-admin.py utility .You'll have Django admin already included and configured for you all you have to do is … -
Two Scoops of Django 1.11 Is Printed!
After longer than we expected, the shiny new print copies of Two Scoops of Django 1.11 are finally ready. We've shipped all pre-orders, and many of you who ordered it in advance should have the book in your hands. We're delighted by how well it's been received, which is due only to the help and encouragement of our readers. Right now you can order the print version of Two Scoops of Django 1.11 at either: Two Scoops Press (for autographed copies directly from us), or Amazon (this link sends you to your regional Amazon store) If you purchase the book on Amazon, please leave an honest review. Simply put, Amazon reviews make or break a book, each one responsible for additional sales. It's our dream that if sales of Two Scoops of Django 1.11 are good enough, we'll be able to justify doing less consulting and instead, writing more technical books. -
Two Scoops of Django 1.11 Is Printed!
After longer than we expected, the shiny new print copies of Two Scoops of Django 1.11 are finally ready. We've shipped all pre-orders, and many of you who ordered it in advance should have the book in your hands. We're delighted by how well it's been received, which is due only to the help and encouragement of our readers. Right now you can order the print version of Two Scoops of Django 1.11 at either: Two Scoops Press (for autographed copies directly from us), or Amazon (this link sends you to your regional Amazon store) If you purchase the book on Amazon, please leave an honest review. Simply put, Amazon reviews make or break a book, each one responsible for additional sales. It's our dream that if sales of Two Scoops of Django 1.11 are good enough, we'll be able to justify doing less consulting and instead, writing more technical books. -
Optimizing and Squashing Django Migrations
Django migrations allow you to change , evolve and upgrade your database schema while keeping any existing database data intact .They also allow you to use version control tools such as Git with databases . In this tutorial we are going to learn how to optimize database migrations by squashing or combining them . Starting with Django 1.7 ,migrations became part of Django itself so you don't need to install any third party apps such as South to work with database migrations . To use migrations you frequently work with two commands which are : python manage.py makemigrations Which generates migration files according to the change in your Django models . And python manage.py migrate Which actually migrates or upgrades the database schema . But there are also other Django commands that can be used in certain situations such as when you need to optimize your migrations . How to squach migrations in Django ? Django has a management command that allows you to squach or combine multiple migration files into a single optimized migration file . You can simply invoke this command using : python manage.py squachmigrations Now lets consider this senario : You have a Django app named … -
How to Add Django Admin Custom List Actions
Django has an Admin package which can be used to scaffold a full CRUD application based on your registered models . This is very useful for prototyping or even for creating working applications . The Admin application is also extensible so you can very easily customize or extend the generated app to meet your preferences and requirements . Lists views in Django Admin are used to show a specific registered model data in tabular format with default bulk actions that can be applied to selected rows . In this tutorial we will see how to extend the Django Admin List views with custom actions . Adding Custom List Actions Actions in Admin app are just regular Python functions that have three parameters : A ModelAdmin An HttpRequest A QuerySet So to add a cutsom action you need to add an action function in admin.py module where you register your models . Lets take a simple real example . First create a Django project then create an app then in : In models.py module we add this Product model # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models class Product(models.Model): sku = models.CharField(max_length=13,help_text="Enter Product Stock Keeping Unit") … -
Optimizing and Squashing Django Migrations
Django migrations allow you to change , evolve and upgrade your database schema while keeping any existing database data intact .They also allow you to use version control tools such as Git with databases . In this tutorial we are going to learn how to optimize database migrations by squashing or combining them . Starting with Django 1.7 ,migrations became part of Django itself so you don't need to install any third party apps such as South to work with database migrations . To use migrations you frequently work with two commands which are : python manage.py makemigrations Which generates migration files according to the change in your Django models . And python manage.py migrate Which actually migrates or upgrades the database schema . But there are also other Django commands that can be used in certain situations such as when you need to optimize your migrations . How to squach migrations in Django ? Django has a management command that allows you to squach or combine multiple migration files into a single optimized migration file . You can simply invoke this command using : python manage.py squachmigrations Now lets consider this senario : You have a Django app named … -
How to Add Django Admin Custom List Actions
Django has an Admin package which can be used to scaffold a full CRUD application based on your registered models . This is very useful for prototyping or even for creating working applications . The Admin application is also extensible so you can very easily customize or extend the generated app to meet your preferences and requirements . Lists views in Django Admin are used to show a specific registered model data in tabular format with default bulk actions that can be applied to selected rows . In this tutorial we will see how to extend the Django Admin List views with custom actions . Adding Custom List Actions Actions in Admin app are just regular Python functions that have three parameters : A ModelAdmin An HttpRequest A QuerySet So to add a cutsom action you need to add an action function in admin.py module where you register your models . Lets take a simple real example . First create a Django project then create an app then in : In models.py module we add this Product model # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models class Product(models.Model): sku = models.CharField(max_length=13,help_text="Enter Product Stock Keeping Unit") … -
Custom Password Less Authentication in Django
Authentication backends allow the ability to change what method checks your users credentials. An Example for the use of custom authentication backend: For web services, ie Facebook authentication, you don't have access to user data like a password. Without password(not like random string) we can't create a user in django. Facebook connect provides you details of the currently authenticated user. But to maintain the login_required decorator or to a user request.user you still need to have them logged in using Django. That's where the Authentication Backend comes in. from django.contrib.auth.backends import ModelBackend from peeldb.models import User class PasswordlessAuthBackend(ModelBackend): """Log in to Django without providing a password. """ def authenticate(self, username=None): try: return User.objects.get(username=username) except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None In your settings.py add AUTHENTICATION_BACKENDS += ( # ... your other backends 'social.auth_backend.PasswordlessAuthBackend', # path to your custom authentication file # appname.filename.classname ) Then to authenticate a registered user, we can override authenticate function without password in our views like user = authenticate(username={{user_email}}) login(request, user) -
EuroPython 2017
EuroPython is the official European conference for the Python programming language. -
Towards Channels 2.0
Outlining my plan for iterating on Channels' design, and what the future might hold for both Django and Python in general. It's been around three years since I came up with the current Channels design - that of pushing everything over a networked "channel layer" and strictly separating protocol handling and business logic - and while it's generally working well for people, I have this feeling it can be improved, and I've been thinking about how for the past few months. This was brought into sharp focus by recent discussion about writing more of a standard interface for asyncio in particular, but also by Tom Christie's recent work on the same subject, so I've written up where my current thinking is to both help people understand where I'm going and to be more transparent about how I think about problems like this. So, let's start by looking at the issues with the current Channels design: You're forced to run everything (and I mean everything) over a networked channel layer. There are good reasons for this - I'll cover them later - but it's a lot to force on people and arguably the biggest dent to smooth scaling of a Channels-based … -
Creating Smaller Docker Images Part #4: Static Binaries
This is the fourth post in a series on making smaller Docker images: static binaries. In the first post I talked about how to create smaller images by writing better Dockerfiles. In the second post I talked about how to squash layers using docker-squash to make smaller images. In the third post I wrote about how to use Alpine Linux as a smaller base image. In this post I'll examine the ultimate when it comes to making smaller images: static binaries. What if your app didn't have any dependencies and didn't need anything at all except the app itself? This is what static binaries achieve. [...] -
Creating Smaller Docker Images Part #4: Static Binaries
This is the fourth post in a series on making smaller Docker images: static binaries. In the first post I talked about how to create smaller images by writing better Dockerfiles. In the second post I talked about how to squash layers using docker-squash to make smaller images. In the third post I wrote about how to use Alpine Linux as a smaller base image. In this post I'll examine the ultimate when it comes to making smaller images: static binaries. What if your app didn't have any dependencies and didn't need anything at all except the app itself? This is what static binaries achieve. [...] -
Django 1.11+ django.contrib.auth Class Based Views - Part 2 - Password Change and Reset
Since we can log in and logout what about managing our password? Learn the power of using the builtin Generic Class Based Views now in django.contrib.auth. They are simple to use once you know about them.Watch Now... -
Domain Name for Django Development Server
Isn't it strange that browsing the web you usually access the websites by domain names, however, while developing a Django website, you usually access it through IP address? Wouldn't it be handy to navigate through your local website by domain name too? Let's have a look what possibilities there are to access the local development server by a domain name. Access via IP Address You probably know the following line by heart since the first day of developing with Django and can type it with closed eyes? (myenv)$ python manage.py runserver When you run a management command runserver, it starts a lightweight Django development server which by default listens to HTTP requests on your local machine's port 8000, whereas by default, HTTP websites are running on the 80 and HTTPS websites are running on 443. Enter http://127.0.0.1:8000 in a browser and you can click through your Django project. Note that this is a local address and it is not accessible from other devices in the network. Other people accessing the same address from their computers will see what is provided by web servers on their own machines, if any web server is running there at all. Each device in a … -
Markdown Cheatsheet
A quick reference to using Mar... -
Ask Vitor #3: Mocking Emails
Phillip Ahereza asks: I’m writing unit tests for my django app and I was wondering if there are any packages for mocking email or if there is any way I could mock sending and receiving of emails. Answer Basically what Django does when you run your test suite is switch your EMAIL_BACKEND to django.core.mail.backends.locmem.EmailBackend, so to prevent your application from sending emails during the tests execution. While using this backend, all emails sent are stored in the outbox attribute of the django.core.mail module. Let’s see one example on how you can use it to test the email outputs and so on. urls.py from django.conf.urls import url from mysite.core import views urlpatterns = [ url(r'^send/$', views.send, name='send'), ] views.py from django.http import HttpResponse from django.core.mail import send_mail def send(request): email = request.GET.get('email') if email and '@' in email: body = 'This is a test message sent to {}.'.format(email) send_mail('Hello', body, 'noreply@mysite.com', [email, ]) return HttpResponse('<h1>Sent.</h1>') else: return HttpResponse('<h1>No email was sent.</h1>') This is a simple view that expects a querystring parameter named email with a valid email address. If the email value fulfill our view requirements, an email is sent to this address. If the email is invalid or no email … -
AJAXify Django Forms
## **Guide is currently under ... -
Django Framework ve Güvenlik
Merhaba arkadaşlar bu yazımda Django Framework ve Güvenlik konusunu ele alacağız. Bildiğiniz üzre Django, python programlama dili ile yazılmış olan bir web uygulaması geliştirme çatısıdır. Biz geliştiricilere sağladığı esneklik, kolaylıklığı ve hızı eklediğimiz de bizim için önemli olan bir web uygulaması geliştirme çatısıdır. Geliştiriciler için tercih edilmesinin en büyük nedeni yapmış olduğumuz web uygulamalarını daha... Django Framework ve Güvenlik yazısı ilk önce Python Türkiye üzerinde ortaya çıktı. -
Django AbstractUser ile Genişletme
User Modelini Genişletme Merhabalar, OneToOneField ile user modelini genişlettik. Fakat AbstractUser kullanarak genişletmek daha akıllıca bir hareket olacaktır. Yeni bir proje başlatıyorsanız, varsayılan Kullanıcı Modeli sizin için yeterli olsa bile özel bir kullanıcı modeline bir şekilde ihtiyaç duyacaksınız. AbstractUser model, varsayılan kullanıcı modeliyle aynı şekilde davranıyor, ancak ihtiyaç ortaya çıkarsa kullanmanız yeterlidir. Model.py giriş yapalım. [crayon-595ebcd4d5558309387880/] User adında... Django AbstractUser ile Genişletme yazısı ilk önce Python Türkiye üzerinde ortaya çıktı. -
Django AbstractUser ile Genişletme
User Modelini Genişletme Merhabalar, OneToOneField ile user modelini genişlettik. Fakat AbstractUser kullanarak genişletmek daha akıllıca bir hareket olacaktır. Yeni bir proje başlatıyorsanız, varsayılan Kullanıcı Modeli sizin için yeterli olsa bile özel bir kullanıcı modeline bir şekilde ihtiyaç duyacaksınız. AbstractUser model, varsayılan kullanıcı modeliyle aynı şekilde davranıyor, ancak ihtiyaç ortaya çıkarsa kullanmanız yeterlidir. Model.py giriş yapalım. #model.py from django.db import models # Özel kullanıcı from django.contrib.auth.models import AbstractUser class User(AbstractUser): #Avatar'ı ekledik. Avatar = models.CharField(max_length=50)User adında bir oluşturduk. User modelini default olarak django’nun algılaması için settings.py’e “AUTH_USER_MODEL” değişkeni ile belirtmemiz gerekiyor. Settings.py giriş yapalım. #settings.py #app : Uygulama adı #User : model adı AUTH_USER_MODEL = 'app.User'Admin panele girdiğimizde “kullanıcılar” bölümü silinmiş olacaktır. Yeni user modelini, admin panele ekliyelim. admin.py giriş yapalım. #admin.py from django.contrib import admin from .models import User from django.contrib.auth.forms import UserChangeForm, UserCreationForm from django.contrib.auth.admin import UserAdmin from django import forms # Kullanıcı seçme ekranı class MyUserChangeForm(UserChangeForm): class Meta(UserChangeForm.Meta): # Yeni model model = User class MyUserAdmin(UserAdmin): # Yeni Form form = MyUserChangeForm # Görünmesi gerekenler list_display = UserAdmin.list_display+('Avatar',) # Yeni alanlar fieldsets = UserAdmin.fieldsets + ( (None, {'fields': ('Avatar',)}), ) #Yeni Kullanıcı oluşturma sınıfı class MyUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): # Yeni model model = User def clean_username(self): username = … -
Django Code Review
We want to help solve problems... -
The Purpose of Business
Businesses exist to create val... -
The Purpose of Business
Businesses exist to create val...