What's new in Django community blogs?

Two Scoops of Django Birthday Giveaway

Jul 24 2017 [Archived Version] □ Published at pydanny under tags  audrey book django python twoscoops

Coldest Spring

Today is a special day. You see, the latest fantasy book I co-authored, Coldest Spring (3rd in the Ambria series), is out AND it's my birthday. In honor of of these occasions, the first book of the series, Darkest Autumn, for 0.99 cents on Amazon. Plus, I'm doing a Python-related giveaway.

The Giveaway: There’s a python programming easter egg in the book. One of the characters mentions the elegance of Python. The first person who tells me in the comments below the name of the father and grandfather of that character gets an autographed Two Scoops of Django 1.11 book shipping anywhere in the world.

Finally, if you want to give me a truly special present for my birthday, please review any or all of my books on Amazon. Positive or negative, every review makes a difference. The positive stuff feeds my already inflated ego, and the negative stuff tells me what I need to do in order to improve.


Is Django the Right Fit for your Project?

Jul 24 2017 [Archived Version] □ Published at Caktus Blog

You need a website. You may have done some searches, and come back overwhelmed and empty-handed, having found hosting providers offering services that may have sounded familiar (“WordPress”) and ones that may have sounded like a foreign language (“cPanel”). You may have considered hiring someone to build your website, and gotten conflicting answers about what...


Mobile Development Languages

Jul 24 2017 [Archived Version] □ Published at tuts+

If you want to code a mobile app, you need to know a programming language. But it can be hard to choose the best language (or languages) for a project. There are a lot of options out there, and in this post I'll help you narrow them down so that you can pick the best.

It all depends on what you're building. For certain apps, mobile developers may not need all the available features of a particular language. In other situations, a single app may require more than one language. In this tutorial, I'll go through various mobile development languages and highlight some of the details that can help you make a decision. 

Let's start with some languages which you may already be familiar with.

Android Languages

Java

According to the TIOBE Index, Java is the most popular programming language as of June 2017. If you want to develop Android apps, you'll most likely to stick to Java. It has a large and established developer community, and that means you can easily get technical support and help. 

So, when you're developing for mobile with Java, you are free to come up with any type of app you can think of. The only limits will be your imagination and the level of your Java knowledge.

Kotlin

Kotlin was designed and developed by JetBrains, the Czech company known for their popular IDE, IntelliJ IDEA. Google's Android team has recently announced that they are officially adding support for the Kotlin programming language. 

Kotlin was developed to address some of the issues in Java. According to the language's fans, Kotlin syntax is simpler, cleaner, and leads to less code bloat. This helps you focus more on solving the actual problem, rather than struggling with verbose syntax. Also, you can use Kotlin and Java together in the same project, and that makes it really powerful.

iOS Languages

Swift

If you want to develop for iOS, Swift might be the language for you. Introduced in 2014 and declared open source in 2015, Swift is swiftly catching up with mobile developers. It's very popular, especially among new iOS development startups. 

Apple has added some great features to the language, such as simplified syntax, the ability to easily pinpoint programmer errors, etc. Apple's huge efforts to promote Swift clearly indicate that it wants this new language to become the mainstream programming language for its app ecosystem.

Objective-C

Objective-C was the original development language for iOS. While the recently introduced Swift language is the future of iOS development, many advanced projects still rely on Objective-C. So the transition from Objective-C to Swift is expected to be somewhat slow, and you may need both of them for some projects, at least for the time being.

Cross-Platform Languages

JavaScript

JavaScript has a long history going back to the early days of the World Wide Web. A very popular front-end and server-side language, it lets web developers do everything from enhancing the user experience of their websites to building complete web apps. 

Today, there are several JavaScript frameworks that specifically target mobile development platforms, such as Ionic 2 and React Native. It's very easy to develop cross-platform mobile apps using these frameworks and libraries. This means you only have to write a single version of your app, and it will run on iOS or Android.

TypeScript

TypeScript is a superset of JavaScript and offers better safety by adding optional static typing. It also provides better support for developing large-scale applications. Developed and maintained by Microsoft, TypeScript allows developers to write cross-platform mobile apps using frameworks such as NativeScript.

Other Languages

C#

C# is the language of Windows Mobile. It's very similar to C++ and Java. Microsoft has adopted some of the features of Java to simplify its architecture, while maintaining the C++ like design. It also has a large and active community of developers who are always friendly and helpful.

C

C is the second most popular language on the TIOBE index, and just like Java, its community is full of seasoned developers who could offer you valuable advice on how to write bug-free code. 

Created by Dennis Ritchie, while working for Bell Labs, C is a widely adopted and powerful language that allows you to directly manipulate low-level operations of a computer. If you want to use Android NDK (Native Development Kit), you'll need to get familiar with the C language.

C++

If you are familiar with C, then you'll really enjoy reading and writing C++ code. C++ is an extension of C, with more high-level features and support for object-oriented programming. C++ is also a favorite language of Android NDK developers. You can use C++ to develop Windows Mobile apps too. C++ goes head to head with Java in the field of software development, and it's really worth mastering.

Python

Python is another popular language that's easy to learn and easy to read. The creators of the language have made extra efforts to keep the syntax as simple and clear as possible. This really helps novice developers maintain high levels of productivity, from day one. If you are comfortable with writing Python code, then you can use frameworks such as Kivy to develop cross-platform mobile apps.

Ruby

Ruby is an object-oriented scripting language, influenced by Ada, C++, Perl, Python, and Lisp. RubyMotion is a great framework for developing native and cross-platform mobile apps in Ruby. It's fairly easy to learn Ruby, thanks to its elegant syntax that focuses on simplicity and productivity.

How to Classify the Languages?

Mobile apps can be grouped into three categories, namely native, hybrid, and native cross-platform. Native apps can fully utilize all the OS facilities and features, and they are the fastest when it comes to performance. However, you need to maintain different codebases for different mobile platforms, as each platform uses different programming languages.

For example, Android platform makes use of Java plus C/C++ to develop native apps. Apple's iOS platform relies on Objective-C and Swift as its native languages. C# is used by Windows Mobile platform to code its native apps. All of these native app programming languages are compiled, rather than interpreted.

Hybrid mobile apps are actually websites that are designed to work with mobile devices too. A user can access them via a mobile browser as if they are visiting a website on a desktop computer. The combination of HTML5, CSS and JavaScript is the obvious choice, if you want to develop web apps.

Recently, a new batch of mobile cross-platform frameworks has emerged. These frameworks combine the best features of native apps and hybrid apps—they're fast and light and can access the full power of the native device, but they also are coded with JavaScript and other web languages, so a lot of code can be reused between platforms.

React Native and NativeScript are popular native cross-platform frameworks. If you want to learn more about these, check out our comprehensive beginner course or some of our many tutorials.

Comparison of Features

Before getting deeper into the detailed language features, you must select a platform. You can refer to the article Mobile Development Platforms to get an idea of various platforms and how to pick the one that suits you best. Assuming that you've already selected a mobile development platform, let's see how these languages compare in terms of their features.

Native Android

If you want to develop for native Android, Java and Kotlin are your obvious choices. So let's have a look at them.

Null Safety

Kotlin has better control over Null references so that the famous NullPointerException bugs (common in Java) are much easier to eliminate. This reduces development time and improves programmer productivity.

Concurrency

Although Java supports concurrent operations, the relevant code may suffer heavily from readability and maintainability issues. Kotlin addresses these issues by using Coroutines. The resulting code is easily readable and easily understandable too.

Type System

Java's type system isn't consistent, and this can sometimes lead to confusion. In particular, the primitive types such as integer, boolean, and so on need to be handled as special cases. By contrast, Kotlin has a relatively simple and more versatile type system that minimizes programmer errors and mistakes.

Supported Programming Styles

Although Java can theoretically support various programming styles, some developers believe that it overly promotes OOP (Object-Oriented Programming). Kotlin doesn't seem to enforce any particular style of programming, so developers have more freedom to choose an approach that fits best. However, Kotlin developers need to have a thorough knowledge of software architecture and development principles.

Which One to Choose?

In a nutshell, it seems that Kotlin is better than Java, but it may take some time for a complete transformation. One challenge is that programmers are used to the thinking patterns enforced by Java. Another is that Kotlin is a new language, and certain features are still experimental.

Anyway, Google has clearly announced that they will offer complete support for Kotlin. In fact, Android Studio, the official Android IDE, now comes with full support for Kotlin. New features and capabilities are constantly added to Kotlin. Over the next few years, we are going to experience a transition period from Java to Kotlin, at least in native Android development.

Native iOS

Objective-C and Swift are the two options you have for iOS development. So let's have a look at each one's features.

Code Syntax

Swift has simpler and clearer syntax to help programmers achieve their goals with the minimum number of LOC (Lines Of Code). This also helps reduce programmer errors and eases bug fixing.

Memory Management

Swift clearly beats Objective-C, when it comes to memory management. Swift enforces more robust and reliable control mechanisms, allowing programmers to avoid undesirable memory leaks.

Performance

Execution of Swift code is much faster than that of Objective-C. This clearly leads to faster app performance and better user experience.

Supported Programming Styles

Unlike Objective-C, Swift has built-in support for functional programming too. So developers don't have to limit themselves to any pre-defined programming styles. That helps developers understand the problem clearly and come up with a better solution.

Which One to Choose?

Just as Kotlin is slowly replacing Java in native Android development, Swift seems sure to thrive in native iOS development, forcing Objective-C to retire. Apple has already started extensive support for Swift, and that's going to get even better in the future. Like Android developers, iOS developers are also experiencing a transition period at the moment. 

While there are several code migration tools available, it may not be possible to fully convert Objective-C projects to Swift without issues. Sometimes, specific workarounds may be required, and that might need a fair knowledge of Objective-C. So the best strategy is to give priority to Swift and learn a bit of Objective-C only when it's absolutely necessary. Also, you need to keep an eye on the latest Swift developments and trends.

Cross-Platform Apps

JavaScript (coupled with other HTML5 technologies) is the most used cross-platform mobile development language. There are also other languages, such as Python and Ruby, but JavaScript has the broadest range of support and adoption. 

Unless you are already a big Ruby or Python fan and you want to try out the cutting-edge of mobile development with those languages, you should stick with JavaScript or its type-augmented sibling, TypeScript.

Conclusion

Choosing a mobile development language can be tricky if you don't understand the features of each one, along with the current industry trends. With this knowledge, though, it's easy to see that choosing a language heavily depends on the particular mobile development platform too.

I'm sure now you have a clearer picture of mobile app development languages and are able to match the relevance of their features to the latest development trends. So just get started coding your next app with confidence!

If you want some help getting started with a new language, check out some of the tutorials and video courses linked throughout this post, or some of our other posts on mobile development!


RMOTR Scholarships for Django Girls

Jul 23 2017 [Archived Version] □ Published at Django Girls Blog

Are you a former Django Girls attendee? Did you find programming interesting and wish to continue web development using Python and Django? Well, we have great news for you.

As Django Girls, we are very excited to announce online scholarships through our new partnership with RMOTR (https://www.rmotr.com/). RMOTR offers interactive online coding classes in which participants are tutored via video conferencing thereby enabling remote learning. RMOTR also provides a pool of other learning resources to learners through their website.


How many scholarships are on offer?

We are super excited to have been offered the following number of scholarships for our Django Girls community by RMOTR:

15 x 25% off tuition scholarships per month.

10 x 50% off tuition scholarships per month.

5 x 100% off tuition (FREE enrollment) scholarships per month.


Who is eligible to apply for these scholarships?

Any member of the Django Girls community is eligible for these scholarships. Admission in one of the scholarships will mean Full and FREE access to all RMOTR courses and tutorials available at http://learn.rmotr.com/. RMOTR also offers a FREE Python course which any member of the Django Girls community can also benefit from.


How do I apply?

To apply, visit https://rmotr.com/apply/?campaign=djangogirls to apply for scholarships in RMOTR courses. The application process involves a small skills test (see this example), which is used to determine if the applicant is in good shape to take the program, or needs some extra help. The applicant is also asked to choose which of the three scholarship options they want to be eligible for, so that can the applicant’s choice is kept in mind while doing the final selection.

The number of scholarships is not fixed but is dependent on the interest from our Django Girls community. More applications from Django Girls means more scholarships awarded to us - YAAY!


Special thanks to our sponsors

We would like to thank RMOTR for sponsoring Django Girls. We look forward to working with you in transforming the lives of women as we introduce them to tech and programming.


Iterating Fast With Django & Heroku

Jul 21 2017 [Archived Version] □ Published at tuts+

Launching an online business can prove to be seriously complicated. Although on paper, it's way easier to create an online business than a bricks-and-mortar one, an entrepreneur can get lost in the multitude of options. Some of the most common pitfalls an online entrepreneur gets stuck in include:

  • Building too much too early: Lose time and burn money building an intricate product. Get demotivated along the way, lose faith in the product, and abandon the project.
  • Believing too much in the idea: Getting stuck to the original idea and not iterating on it, even though customers don't show up, don't pay, or are not satisfied.
  • Failing to start: When somebody starts along the path of building a web project, he/she can get overwhelmed by the seemingly infinite decisions and choices that have to be made. What hosting to use? What platform? What WordPress theme? How to build a high-converting landing page? What programming language and what database? Should you use a web framework? Vanilla JavaScript or jQuery for the front end? Maybe a more complex front-end framework because the project will need one once it's mature enough?
  • Failing to launch: When building a web project, even though you decided on your technology stack, you can get overwhelmed by the feedback you're getting. Counterintuitively, it's considered a mistake to listen to too much feedback. It can be the feedback from people that wouldn't be using your product anyway. People tend to have an opinion about everything, even though they are not completely knowledgeable in the field.

Given the multitude of ways one can fail along the road, it's really important to:

  • Build as little and as quickly as possible, showing it to people who you consider to be potential customers: Minimise costs and effort.
  • Put it online as soon as possible: Get feedback from people on the product, not on your abstract idea.
  • Make changes quickly: When learning what the customer wants, it's crucial to be agile and serve your first paying customers well.

Here's where prototyping comes into place. An entrepreneur should run lean, not wasting time and resources. Building as little as possible at the beginning can prove a virtue. 

There are many schools of thought on what a prototype is and how it should be created. Some say that it should be only a landing page, others that it should be a stripped-down version of the final product. I'm more of a fan of the second. Using only a landing page can feel scammy. Also, you can't get feedback on how you are solving the problem, but rather only on if the problem is worth solving.

Here's the toolbelt of a smart prototyping online entrepreneur:

  • Front-End Frameworks: Bootstrap, Foundation, jQuery, Vue, etc. Using a front-end framework will make your apps work on different screen sizes and different browsers, with a decent design.
  • Back-End Frameworks: Django, Ruby on Rails, Laravel. Using back-end frameworks will help you easily deal with HTML templates, HTTP forms, database access, URL schemas, etc.
  • Platform-as-a-Service: Heroku, Google App Engine, AWS Elastic Beanstalk. Choosing a PaaS can free you from the pain of managing servers, log aggregation, uptime monitoring, deployment infrastructure and more.

In this tutorial, we'll be building a simple application in the spirit of rapid prototyping. We'll be using Django, Bootstrap CSS, and Heroku. The focus will be on the back-end part rather than the front end. 

We're going to take advantage of the Heroku platform to put something online early and to quickly deploy new features. We're going to use Django to build complex database models and functionality. Bootstrap CSS will give us a sensible default style for our pages. Enough talking, let's go.

What We're Building

Make sure you're sitting down for this one. The idea will knock your socks off. Here's the pitch: Don't you just hate how you get all these discount codes but you forget to use them and they expire? 

Wouldn't it be cool to store the codes somewhere where you can search them and also be notified when they're about to expire? I know, great idea, right? Well, put your credit card down, you won't be investing in this one. You're going to build it.

Getting Started

In this tutorial, I'm going to use Python 3. If you are using Python 2.7, the changes should be fairly easy. I'm also going to assume that you're familiar with setuptools, Python virtualenvs, and Git. One more thing before going forward: make sure you have a GitHub and a Heroku account. To use Heroku, you also need to install the Heroku CLI

Let's start by creating a virtualenv:

As you've probably figured out, our application name is Coupy. Let's switch to the new virtualenv, $ workon coupy, and install Django: 

Go into your GitHub account and create a new project. Next, let's clone that project:

The next logical step is to create a Django project. To deploy a Django project to Heroku, we need to follow some guidelines. Fortunately, we can use a project template for that. Here's how to do that:

You might need to move around some folders. Make sure your repository root folder looks like this:

Let's now install the requirements provided by the template:

We now want to push the newly created files to GitHub:

Let's see if what we've done so far works:

Now open a browser window and go to http://localhost:8000. If all is good, you should see the classic Django Welcome page. To make sure that all is good from Heroku's perspective, we can also run the application like this:

To prove how quickly we can go online, let's make our first deploy to Heroku:

We have now created a Heroku application, but we haven't sent any code to Heroku. Notice that Heroku created a user-friendly app id. Here's the output you should get:

We now need to associate our repo with the newly created Heroku app:

Awesome, you just deployed an app to Heroku. It doesn't do much, but you put something online in record time. Good job.

Setting Up the Database

You probably won't ever build a non-trivial web app without a database. The database is the data storage part of the web app. Here's where the web app keeps its state (at least most of it). Here's where we keep the user accounts and the login details and much, much more. Heroku provides a managed PostgreSQL service. 

That's what we're going to use. Make sure you have installed Postgres on your machine and create a database instance to use in our application. Heroku needs an environment variable to be set to be able to connect to the database service. The variable we need to set is DATABASE_URL:

Let's now tell Django to apply the migrations and create the necessary tables:

Let's create a superuser and login to the admin interface at http://localhost:8000/admin:

We can see that the tables have indeed been created. Heroku already associated a database instance to your app by default. You can make sure that's the case by checking in Heroku HEROKU_APP_ID > Settings > Config Variables in your Heroku online console. You should see here that the DATABASE_URL is set to a Heroku generated database address. 

We now have to run the migrations and create the super user commands online. Let's see if it all works as expected:

If all went well, if we visit https://<HEROKU_APP_ID>.herokuapp.com/admin/, we should be able to log in with the credentials we just provided.

User Authentication

In this section, we're going to initialize a Django app and use Django predefined components to create the user authentication functionality in our app.

Inside the new app, we're going to create a urls.py file:

Here we use three generic Django views:

  • RedirectView: Since the base URL of the application doesn't do anything, we're redirecting to the login page.
  • LoginView: Django predefined view that creates the login form and implements the user authentication routine.
  • LogoutView: Django predefined view that logs a user out and redirects to a certain page.

Add the main application to the INSTALLED_APPS list:

Hook up the main.urls to the root URL schema:

In order to display the forms properly, with styles and classes and everything, we need to install django-widget-tweaks:

Add django-widget-tweaks to INSTALLED_APPS:

We now add these two configs to settings.py:

  • LOGIN_REDIRECT_URL: Tells Django where to redirect a user after a successful authentication.
  • LOGOUT_REDIRECT_URL: Tells Django where to redirect the user after he/she logs out.

Let's write a simple master template base.html and a dashboard.html template that extends it. We'll get back to the dashboard one later.

Write the view that renders the dashboard.html template:

We're all set. Head over to http://localhost:8000/login/ and test that authentication works. Next, save your progress:

Create the Coupon Model

Now we've come to the most important part of our application, designing the Coupon model. We'll be installing django-model-utils to add some extra properties to our models.

Write the Coupon model:

The django-model-utils models we extended enable us to:

  • TimeStampedModel helps us track when the model was placed in the database, via the created field.
  • TimeFramedModel adds the start and end fields to our model. We're using these fields to keep track of the coupon's availability.

Hook the model to the admin:

Create and apply migrations:

Save progress:

ModelForm for Coupon Creation

One of the cool features of Django is the ability to create forms from model classes. We're going to create such a form that enables users to create coupons. Let's create a forms.py file inside the main application:

Let's add this form to the dashboard. We need to change both the view and the template:

We now have a way to create coupons from the dashboard. Go give it a try. We have no way of seeing the coupons in the dashboard, but we can do so in the admin panel. Let's save the progress:

Expiring Soon Coupons

One more thing we want to be displayed in the dashboard: coupons that expire soon, for example ones that expire this week.

Add django.contrib.humanize to INSTALLED_APPS to display dates in the templates in a human-friendly way.

Let's enhance the view so that it fetches the soon expiring coupons and passes them to the template context:

Let's update the template so that it displays the expiring coupons in a tabular way. We'll also put the creation form and the table in two separate columns using Bootstrap's grid system:

Looking good. Save your progress:

Catalogue View

Let's now learn some other Django shortcuts to create a view that displays the list of coupons we have available. We're talking about generic views. Here's how to quickly create a ListView:

Now tie the view in your URL schema:

Create the template catalogue.html:

Since we've hooked everything up, head over to http://localhost:8000/catalogue/ to view your coupon catalogue.

Save the progress:

This is pretty close to an MVP. I encourage you to do some fine tuning like creating a navbar, login/logout/register buttons, etc. The important thing is that you understand the process of prototyping and getting your product out there for people to see it. Speaking of which, our product is not online yet. We didn't push the latest version to Heroku. Let's do that and then pick up the phone and call the investors.

Conclusion

We created a simple but practical application. We created features quickly, and we've deployed them online so that our potential customers can use them and give us feedback. It's better to show people rather than only talk about an idea. 

Here are some conclusions we can draw:

  • Picking the right tools can significantly speed up the development process.
  • The tools used for prototyping aren't always the best choice for more mature projects. Keeping that in mind, it's better to use more agile tools early on and iterate on them rather than getting lost in minute implementation details early on.
  • Taking advantage of a PaaS means that the applications have to respect a few design patterns. Usually these patterns make sense, and they force us to write even better code.
  • Django has a lot of shortcuts that make our lives easier:
    • Django ORM helps with database access. No need to worry about writing correct SQL and being extra careful with syntax errors.
    • Migrations help us version and iterate on the database schema. No need to go and write SQL to create tables or add columns.
    • Django has a plugin-friendly architecture. We can install apps that help us achieve our goals quicker.
    • Generic views and model forms can inject some of the most common behaviors: listing models, creating models, authentication, redirection, etc.
  • When launching, it's important to be lean and fast. Don't waste time, and don't spend money.


Django Workflow

Jul 20 2017 [Archived Version] □ Published at Latest Django packages added


Django Anti-Patterns: Signals

Jul 18 2017 [Archived Version] □ Published at Lincoln Loop

Django's Signal Dispatcher is a really powerful feature that you should never use. Ok, it has valid use cases, but they may be rarer than you think.

First, to dispell a misconception about signals, they are not executed asynchronously. There is no background thread or worker to execute them. Like most of Django, they are fully "synchronous". I suspect this misconception stems from the event-driven coding pattern they use which is often seen in asynchronous languages/libraries.

The event-driven pattern of signals looks neat at first, but often I see them mentioned as a source of frustration. It's not the author complaining, but the poor soul who inherits maintenance of the code and only learns of the existitance of signals when trying to track down unexpected behavior.

Consider the following example using signals:

# File: models.py
from django.db import models

class Pizza(models.Model):
    has_pepperoni = models.BooleanField(default=False)
   
class ToppingSales(models.Model):
    name = models.CharField(max_length=100, unique=True)
    units_sold = models.PositiveIntegerField(default=0)
# File: signals.py
from django.db.models.signals import post_save
from django.db.models import F
from django.dispatch import receiver
from .models import Pizza

def pizza_saved_handler(sender, instance, created, **kwargs):
    if created and instance.has_pepperoni:
        ToppingSales.objects.filter(name='pepperoni').update(
            units_sold=F('units_sold') + 1)
# File: app.py
from django.apps import AppConfig
from django.db.models.signals import post_save

class PizzeriaConfig(AppConfig):

    def ready(self):
        from .models import Pizza
        from .signals import pizza_saved_handler
        post_save.connect(pizza_saved_handler, sender=Pizza)

Compare that to an example without signals:

# File: models.py
class Pizza(models.Model):
    has_pepperoni = models.BooleanField(default=False)
   
    def save(self, *args, **kwargs):
        created = self.pk is None
        super(Pizza, self).save(*args, **kwargs)
        if created and self.has_pepperoni:
            ToppingSales.objects.filter(name='pepperoni').update(
                units_sold=F('units_sold') + 1)           
   
class ToppingSales(models.Model):
    name = models.CharField(max_length=100, unique=True)
    units_sold = models.PositiveIntegerField(default=0)

This is a contrived example, but it gets the point across. With signals, we have to spread the logic across three different files. Worse, the standard for putting signals in a signals module is not always followed, especially in older code bases. Simply finding where the signals are defined and connected can be a challenge. The example without signals is not only less code, but far easier to read, understand, and test. You can see all the side-effects of Pizza model creation, simply by reading the code of the Pizza model.

But breaking up the code is a good thing, right? I agree, but not when it inhibits readability. The intent here is not to define all the logic in the save method, but to leave a breadcrumb for future developers so they can see what code is executed when a save occurs. With that in mind, a function or method call in the save method will help developers follow the path the code takes. That may look like this:

class Pizza(models.Model):
    has_pepperoni = models.BooleanField(default=False)
    
    def _update_toppings(self, created=False):
        if created and self.has_pepperoni:
            ToppingSales.objects.filter(name='pepperoni').update(
                units_sold=F('units_sold') + 1)  
   
    def save(self, *args, **kwargs):
        created = self.pk is None
        super(Pizza, self).save(*args, **kwargs)
        self._update_toppings(created)

By simply overriding your model's save and delete methods, you can accomplish almost anything the {pre,post}_{save,delete} signals can and make your code easier to read in the process. Similarly, request_{started,finished} could be accomplished by middleware instead. With the new class-based login views, even the django.contrib.auth signals can be replaced with a straight-forward subclass.

So... Never use signals?

Not quite. Signals are still valuable in a few limited scenarios.

  1. Extending the functionality of a third-party library. If you're using an app with models where you don't control the code, signals are a more robust alternative to monkey-patching for taking specific actions on save or delete.
  2. Delete signals work on the delete queryset method. If you'd like the same actions to happen on both single object and queryset deletes, a signal is probably your best bet. Note: Due to the way the SQL is generated, this does not apply to the update queryset method (with save signals). Another frequent source of confusion/bugs.
  3. When the you need to apply the same signal handler to many models. If you just have a few, I'd still favor overriding the save/delete method and calling a shared function. For more than a few, copy/pasting the save method everywhere becomes more error-prone and signals look like a better option.
  4. Avoiding tight cross-application dependencies. If you need to cross application boundaries, especially when the application may be used in multiple projects, signals may be better for looser coupling between the apps. Be careful with this one though. Use it because you need to, not because you think you might want it in the future.

If you must use signals, think twice and determine if you really need them or are just being clever. Consider your future self and the violent psycopath who will be maintaining your code. By documenting them copiously, using some logging, and leave lots of breadcrumbs you can use them safely and prevent future frustration.


django-common

Jul 18 2017 [Archived Version] □ Published at Latest Django packages added


Caktus at DjangoCon2017

Jul 17 2017 [Archived Version] □ Published at Caktus Blog

In less than a month we’ll be heading out to Spokane, WA for DjangoCon 2017. We’re proud to be attending as sponsors for the eighth year, and look forward to greeting everyone at our booth. On August 16th, we’ll be raffling off a GoPro Session action camera, so be sure to stop by and enter....


django-firefence

Jul 16 2017 [Archived Version] □ Published at Latest Django packages added

Like a firewall but smaller. Protect your views from intruders!


Introducing NumPy

Jul 14 2017 [Archived Version] □ Published at tuts+

Numeric is a package that was originally developed by Jim Hugunin. It is considered the ancestor of NumPy, a Python library and an open-source project created by Travis Oliphant which stands for Numerical Python. Travis created NumPy by incorporating features of the Numarray package into Numeric. 

The fundamental idea of NumPy is support for multidimensional arrays. So NumPy can be considered as the base for numerical computing in Python, and has been created to enable Python to be used in solving mathematical and scientific problems. The NumPy module provides us with hundreds of useful mathematical functions in addition to constants such as the base of natural logarithms (e) and pi (π).

This tutorial shows how we can use NumPy to work with multidimensional arrays, and describes the ndarray object, a fundamental object of the library.

Installing NumPy

Since Python doesn't come bundled with NumPy, the first step to use this library is to go ahead and install it. This can be simply done by running the following command in your command prompt:

To make sure that NumPy was installed successfully, run the following commands in Python's IDLE:

Python-IDLE-Numpy

If the import statement at least runs successfully, then you are all set!

The ndarry Object

The ndarray is a fundamental object of NumPy. This object is an N-dimensional array, meaning that it contains a collection of elements of the same type indexed using N (dimensions of the array) integers.

The main attributes of ndarray are data type (dtype), shape, size, itemsize, data, and ndim. Let's learn what each attribute means through an example. 

In this example we are going to use NumPy to create an array. I will not give the dimensions of the array and other information, as we will see that using the above attributes.

create_array_numpy

Notice that we used the array function to create an array. The output of the above script is as follows:

array_numpy_output

Let's now return to our attributes.

dtype

The dtype attribute can be run as shown in the following statement:

The above statement will return int32 as the data type. This means that the elements of the array are of type int32. I'm getting 32 as I'm using a 32-bit Python. If you are using a 64-bit Python, you will get int64, but we are dealing with integers at the end.

Since NumPy is used in scientific computing, it has many data types, as shown in the documentation. Notice that the majority of the NumPy data types end with a number, which indicates the number of bits associated with that type (this was mentioned briefly in the above paragraph).

The following examples show how we can convert from one type to another:

The above statements return the following:

Although we can convert from one type to another, it is important to note that we cannot convert a complex number into an integer or a float.

shape

The shape attribute returns a tuple of the array dimensions. So the following statement:

will return (4,4), meaning that our array is composed of 4 rows and 4 columns.

size

The size attribute returns the number of elements in the array. Thus, if we type:

we will get 16 as the result, meaning that we have 16 elements in our array.

itemsize

The itemsize attribute returns the size of one array element in bytes. The following statement:

will return 4. This means that each array element is of size 4-bytes.

data

The data attribute is a Python buffer object that points to the start of the array's data. If we type the following:

we will get the following: <memory at 0x0000021E7E8D7EA0>.

ndim

The attribute ndim will return the number of the array dimensions. So typing the following statement:

will return 2, that is the array consists of two dimensions.

After understanding what the different ndarray attributes mean, let's take a look at some more examples of using ndarray.

Example 1

Say we want to create a new array with one row and five columns. We would do that as follows:

The output of the above statement is: [1 2 3 4 5].

Example 2

In this example, I'm going to rewrite the first example in this tutorial, but using [ ] instead of ( ), as follows:

numpy_array_square_brackets

Example 3

This example shows how we use a structured data type, where we declare the field name and the corresponding data type:

If we print(data_type), we will get the following:

We can apply the height_type to an ndarray object, as follows:

Selecting Items

In this section I'm going to show you how to select specific items in the array. For our array shown above under the "ndarry Object" section, let's say we want to select the item located on the third row and the fourth column. We will do that as follows:

Remember that indexing here starts at 0, and that's why we wrote [2,3] instead of [3,4].

More on NumPy Arrays

In this section, we are going to delve deeper into NumPy arrays.

Empty (Uninitialized) Arrays

We can create an empty array using numpy.empty with the following syntax:

The meanings of the parameters in the above constructor are as follows

  • Shape: the shape (dimensions) of the empty array.
  • dtype: the desired output type, which is optional.
  • Order: if you want a C-style (row-major) array, you would type C; if you want a FORTRAN-style (column-major) array, you would type F.

So let's create an empty [2,2] array of type int. We can do that as follows:

The above script will return the following random values as the array wasn't initialized:

Array Filled With Zeros

In order to create an array where the elements are all zeros, we use numpy.zeros. The constructor here has the same syntax and parameters as in numpy.empty. So, if we want to create a [2,2] zeros array of type int, we can do that as follows:

The above script will return the following:

An array with all elements having the value 1 can be simply created in the same way as above, but with numpy.ones.

Arrays With Evenly Spaced Values Within a Given Range

We can use numpy.arange to create an array with evenly spaced values within a specified range. The constructor has the following format:

Below is the meaning of each parameter:

  • Start: this is where the interval begins. The default value is 0.
  • Stop: the end of the interval, provided that this number is not included.
  • Step: the spacing between values. The default value is 1.
  • dtype: the data type of the output. If not specified, the data type will be the same as that of the input.

Let's take an example of numpy.arange.

The result of the above script is:

Reshaping an Array

In order to reshape an array, we use the numpy.reshape function. This function gives a new shape to an array without changing its data. As shown in the documentation, the function has the following attributes: numpy.reshape(a, newshape, order='C'), where a is the array we would like to reshape, newshape is the new desired shape provided that the new shape should be compatible with the origin shape, and order is an optional argument which refers to the index order we would like to use to both read the array a and how we would like to place the elements in the reshaped array.

C means reading/writing the elements using C-like index order; F means reading/writing the elements using Fortran-like index order, and A means reading/writing the elements in Fortran-like index order if a is Fortran contiguous in memory, C-like order otherwise.

I know I've covered a lot in the above paragraph, but the concept is very simple. Let's take our original array my_array and try to reshape it. Remember that the new array (reshaped array) has to be compatible with the original array. For instance, my_array has the shape (4,4), that is we have 16 elements in the array, and the new array has to have that number of elements.

We can reshape my_array by setting it to have eight rows and two columns, as follows:

In which case we would have the following output, where we also have 16 elements.

What if we write the reshape statement as follows?

In this case, you would get the following error:

Concatenating Arrays

If we want to join two or more arrays of the same shape along a specific axis, we can use the numpy.concatenate function. The syntax of this function is: numnumpy.concatenate((a1, a2, ...), axis=0)y.concatenate. a1 and a2 are arrays having the same shape, and axis is the axis along which the arrays will be joined, provided that the default is 0.

Again, let's take an example to simplify the concept. In this example, we will be joining (concatenating) three arrays.

The output of the above code is as follows:

Splitting Arrays

Contrary to joining arrays as shown in the above section, let's see how we can split (divide) an array into multiple sub-arrays. This can be done using the following function:

ary is the array to be divided into sub-arrays. Regarding indices_or_sections, if it is an integer N, the array will be divided into N equal arrays along the axis. If it is a 1-D array of sorted integers, the entries indicate where along the axis the array is split. axis is the axis along which to split.

The following example will reverse what we have done in the previous example, that is to return the concatenated array into its three array constituents:

The output of the above script is:

Conclusion

As we saw in this tutorial, NumPy makes it very flexible to work with arrays. The tutorial was just a scratch on the surface of this interesting Python library. NumPy still has many more features to look at to get the most out of this library. A comprehensive book on the topic by the NumPy creator himself is Guide to NumPy.

Furthermore, see what we have available for sale and for study in the marketplace, and don't hesitate to ask any questions and provide your valuable feedback using the feed below.


django-webpack-static

Jul 14 2017 [Archived Version] □ Published at Latest Django packages added

Webpack static loader for Django


Two Scoops of Django 1.11 Is Printed!

Jul 13 2017 [Archived Version] □ Published at pydanny under tags  audrey book class-based-views django python

Two Scoops of Django

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.


Over 10,000 women have attended a Django Girls workshop!

Jul 12 2017 [Archived Version] □ Published at Django Girls Blog

If you’re really quiet and listen super hard, you might be able to hear the Django Girls team celebrating the latest milestone…

This month the Django Girls Foundation helped support over 10,000 people learn to code with the Django Girls tutorial! Of course, we couldn’t have done it without the hard work and dedication of our 947 volunteers who organised the 441 events over the past three years!

Go team! 


Texting Centre

Jul 11 2017 [Archived Version] □ Published at Latest Django packages added


django-planet aggregates posts from Django-related blogs. It is not affiliated with or endorsed by the Django Project.

Social Sharing

Feeds

Tag cloud

admin administration adsense advanced ajax amazon angular angularjs apache api app appengine app engine apple application security aprendiendo python architecture argentina articles asides audrey aurelia australia authentication automation backup bash basics best practices binary bitbucket blog blog action day blogging book books buildout business c++ cache capoeira celery celerycam celerycrawler challenges chat cheatsheet cherokee choices christianity class-based-views cliff clojure cloud cms code codeship codeship news coding command community computer computers computing configuration consumernotebook consumer-notebook continuous deployment continuous integration cookiecutter couchdb coverage css custom d data database databases db debian debugging deploy deployment deployment academy design developers development devops digitalocean django django1.7 django admin django cms djangocon django framework django-nose django-readonly-site django-rest-framework django-tagging django templates django-twisted-chat django web framework tutorials documentation dojango dojo dotcloud dreamhost dughh easy_install eclipse education elasticsearch email encoding english error europe eventbrite events expressjs extensions fabric facebook family fashiolista fedora field file filter fix flash flask foreman form forms frameworks friends fun functional reactive programming gae gallery games geek general gentoo gis git github gmail gnome goals google google app engine guides gunicorn hack hackathon hacking hamburg haskell heroku holidays hosting howto how-to howtos how-tos html http i18n image imaging indifex install installation intermediate internet ios iphone java javascript jinja2 jobs journalism jquery json justmigrated kde la latex linear regression linkedin linode linux login mac machine learning mac os x markdown math memcached meme mercurial meta meteor migration mirror misc model models mod_wsgi mongodb months mozilla multi-language mvc mysql nasa nelenschuurmans newforms news nginx nodejs nosql oauth ogólne openshift opensource open source open-source openstack operations orm osx os x ottawa paas packages packaging patterns pedantics pelican penetration test performance personal personal and misc philippines philosophy php pi pil pinax pip piston planet plone plugin pony postgis postgres postgresql ppoftw presentation private programmieren programming programming &amp; internet project projects pycharm pycon pycon-2013-guide pydiversity pygrunn pyladies pypi pypy pyramid python python3 queryset quick tips quora rabbitmq rails rant ratnadeep debnath reactjs recipe redis refactor release request resolutions rest reusable app review rhel rtnpro ruby ruby on rails scala scaling science screencast script scripting security server setup shell simple smiley snaking software software collections software development south sphinx sprint sql ssh ssl static storage supervisor support svn sysadmin tag tag cloud talk nerdy to me tastypie tdd techblog technical technology template templates template tags test testing tests tip tips tools tornado training transifex travel travel tips for geeks tumbles tutorial tutorials twisted twitter twoscoops typo3 ubuntu uncategorized unicode unittest unix use user authentication usergroup uwsgi uxebu vagrant validation virtualenv virtualenvwrapper web web 2.0 web application web applications web design &amp; development webdev web development webfaction web framework websockets whoosh windows wordpress work workshop wsgi yada year-end-review znc zope