Django

What is Django?
(https://www.djangoproject.com/)
Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source.

With Django, you can take Web applications from concept to launch in a matter of hours. Django takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel.

Ridiculously fast
Django was designed to help developers take applications from concept to completion as quickly as possible.

Fully loaded
Django includes dozens of extras you can use to handle common Web development tasks. Django takes care of user authentication, content administration, site maps, RSS feeds, and many more tasks — right out of the box.

Reassuringly secure
Django takes security seriously and helps developers avoid many common security mistakes, such as SQL injection, cross-site scripting, cross-site request forgery and clickjacking. Its user authentication system provides a secure way to manage user accounts and passwords.

Exceedingly scalable
Some of the busiest sites on the planet use Django’s ability to quickly and flexibly scale to meet the heaviest traffic demands.

Incredibly versatile
Companies, organizations and governments have used Django to build all sorts of things — from content management systems to social networks to scientific computing platforms.

Getting started with Django
(https://www.djangoproject.com/start/)

It’s quick & easy to get up and running with Django.

Depending how new you are to Django, you can try a tutorial, or just dive into the documentation.

Want to learn more about Django? Read the overview to see whether Django is right for your project.

Django overview

Install Django

Before you can use Django, you’ll need to install it. Our complete installation guide covers all the possibilities; this guide will get you to a simple, minimal installation that’ll work while you walk through the introduction.

Django installation guide

Write your first Django app

Installed Django already? Good. Now try this tutorial, which walks you through creating a basic poll application. It’s got two parts:

  1. A public site that lets people view polls and vote in them.
  2. An administrative interface that lets you add, change and delete polls.

Take the tutorial

Sharpen your skills

The official Django documentation covers everything you need to know about Django (and then some).

Read the docs

Intro to Django

  • Object-relational mapper

    Define your data models entirely in Python. You get a rich, dynamic database-access API for free — but you can still write SQL if needed.

    Read more

    class Band(models.Model):
        """A model of a rock band."""
        name = models.CharField(max_length=200)
        can_rock = models.BooleanField(default=True)
    
    
    class Member(models.Model):
        """A model of a rock band member."""
        name = models.CharField("Member's name", max_length=200)
        instrument = models.CharField(choices=(
                ('g', "Guitar"),
                ('b', "Bass"),
                ('d', "Drums"),
            ),
            max_length=1
        )
        band = models.ForeignKey("Band")      
    
  • URLs and views

    A clean, elegant URL scheme is an important detail in a high-quality Web application. Django encourages beautiful URL design and doesn’t put any cruft in URLs, like .php or .asp.

    To design URLs for an application, you create a Python module called a URLconf. Like a table of contents for your app, it contains a simple mapping between URL patterns and your views.

    Read more

    from django.conf.urls import url
    
    from . import views
    
    urlpatterns = [
        url(r'^bands/$', views.band_listing, name='band-list'),
        url(r'^bands/(\d+)/$', views.band_detail, name='band-detail'),
        url(r'^bands/search/$', views.band_search, name='band-search'),
    ]
          
    
    from django.shortcuts import render
    
    def band_listing(request):
        """A view of all bands."""
        bands = models.Band.objects.all()
        return render(request, 'bands/band_listing.html', {'bands': bands})      
    
  • Templates

    Django’s template language is designed to strike a balance between power and ease. It’s designed to feel comfortable and easy-to-learn to those used to working with HTML, like designers and front-end developers. But it is also flexible and highly extensible, allowing developers to augment the template language as needed.

    Read more

    <html>
      <head>
        <title>Band Listing</title>
      </head>
      <body>
        <h1>All Bands</h1>
        <ul>
        {% for band in bands %}
          <li>
            <h2><a href="{{ band.get_absolute_url }}">{{ band.name }}</a></h2>
            {% if band.can_rock %}<p>This band can rock!</p>{% endif %}
          </li>
        {% endfor %}
        </ul>
      </body>
    </html>      
    
  • Forms

    Django provides a powerful form library that handles rendering forms as HTML, validating user-submitted data, and converting that data to native Python types. Django also provides a way to generate forms from your existing models and use those forms to create and update data.

    Read more

    from django import forms
    
    class BandContactForm(forms.Form):
        subject = forms.CharField(max_length=100)
        message = forms.CharField()
        sender = forms.EmailField()
        cc_myself = forms.BooleanField(required=False)      
    
  • Authentication

    Django comes with a full-featured and secure authentication system. It handles user accounts, groups, permissions and cookie-based user sessions. This lets you easily build sites that let users to create accounts and safely log in/out.

    Read more

    from django.contrib.auth.decorators import login_required
    from django.shortcuts import render
    
    @login_required
    def my_protected_view(request):
        """A view that can only be accessed by logged-in users"""
        return render(request, 'protected.html', {'current_user': request.user})      
    
  • Admin

    One of the most powerful parts of Django is its automatic admin interface. It reads metadata in your models to provide a powerful and production-ready interface that content producers can immediately use to start managing content on your site. It’s easy to set up and provides many hooks for customization.

    Read more

    from django.contrib import admin
    from bands.models import Band, Member
    
    class MemberAdmin(admin.ModelAdmin):
        """Customize the look of the auto-generated admin for the Member model"""
        list_display = ('name', 'instrument')
        list_filter = ('band',)
    
    admin.site.register(Band)  # Use the default options
    admin.site.register(Member, MemberAdmin)  # Use the customized options      
    
  • Internationalization

    Django offers full support for translating text into different languages, plus locale-specific formatting of dates, times, numbers and time zones. It lets developers and template authors specify which parts of their apps should be translated or formatted for local languages and cultures, and it uses these hooks to localize Web applications for particular users according to their preferences.

    Read more

    from django.shortcuts import render
    from django.utils.translation import ugettext
    
    def homepage(request):
        """
        Shows the homepage with a welcome message that is translated in the
        user's language.
        """
        message = ugettext('Welcome to our site!')
        return render(request, 'homepage.html', {'message': message})
          
    
    {% load i18n %}
    <html>
      <head>
        <title>{% trans 'Homepage - Hall of Fame' %}</title>
      </head>
      <body>
        {# Translated in the view: #}
        <h1>{{ message }}</h1>
        <p>
          {% blocktrans count member_count=bands.count %}
          Here is the only band in the hall of fame:
          {% plural %}
          Here are all the {{ member_count }} bands in the hall of fame:
          {% endblocktrans %}
        </p>
        <ul>
        {% for band in bands %}
          <li>
            <h2><a href="{{ band.get_absolute_url }}">{{ band.name }}</a></h2>
            {% if band.can_rock %}<p>{% trans 'This band can rock!' %}</p>{% endif %}
          </li>
        {% endfor %}
        </ul>
      </body>
    </html>      
    
  • Security

    Django provides multiple protect

Writing your first Django app, part 1
(https://docs.djangoproject.com/en/1.10/intro/tutorial01/)

Let’s learn by example.

Throughout this tutorial, we’ll walk you through the creation of a basic poll application.

It’ll consist of two parts:

  • A public site that lets people view polls and vote in them.
  • An admin site that lets you add, change, and delete polls.

We’ll assume you have Django installed already. You can tell Django is installed and which version by running the following command:

$ python -m django --version

If Django is installed, you should see the version of your installation. If it isn’t, you’ll get an error telling “No module named django”.

This tutorial is written for Django 1.10 and Python 3.4 or later. If the Django version doesn’t match, you can refer to the tutorial for your version of Django by using the version switcher at the bottom right corner of this page, or update Django to the newest version. If you are still using Python 2.7, you will need to adjust the code samples slightly, as described in comments.

Writing your first Django app, part 2
(https://docs.djangoproject.com/en/1.10/intro/tutorial02/)

This tutorial begins where Tutorial 1 left off. We’ll setup the database, create your first model, and get a quick introduction to Django’s automatically-generated admin site.


Tango With Django
(http://www.tangowithdjango.com/)

Tango With Django 1.9

A beginner’s guide to web development with Python / Django 1.9

We are currently in the process of updating the book to Django 1.9.

Tango With Django 1.7

A beginner’s guide to web development with Python 2.7 / Django 1.7

Tango With Django 1.5.4

A beginner’s guide to web development with Python 2.7 / Django 1.5.4

Setting up your Python 2.7 development environment is an important part of any project. Here we show you how to set up your environment and project so that you can deploy your application in next to no time.

This book has been designed to get you going fast and to learn by example. You’ll learn the key aspects of the Python Django Framework by developing an application called Rango.

o get you working with the Python Django Framework, and not against it, we have provided workflows to help you fall into line with the Model-View-Template architecture.

On many occasions we’ve seen clever students get stuck, spending hours trying to fight with Django and other aspect of web development, usually because a key piece of information was not provided or something was not clear. While the occasional blip might set you back 10-15 minutes, sometimes they can take hours to resolve. We’ve tried to remove as many of these hurdles as possible. This will mean you can get on with developing your application, and not figuring out another piece of the puzzle.

Web application frameworks can save you a lot of hassle and lot of time, well, that is, if you know how to use them! Often the learning curve is steep. This book tries to get you going, and going fast. By showing you how to put together a web application with all the bells and whistle from the onset, the book shortens this curve.

Using web application frameworks requires you to pick up and run with a particular design pattern – so you only have to fill in certain pieces in certain places. After working with many students, we heard lots of complaints about using web application frameworks, about how they take control away from them (i.e. inversion of control). To help you we’ve created a number of workflows to focus your development process so that you can regain that sense of control and build your web application in a disciplined mannered.

Whatever you do, do not read this book! It is a hands-on guide to building web applications in Python Django, reading is not doing. To increase the value you gain from this experience, go through and develop the application. When you code up the application, do not just cut and paste the code. Type it in, think about what it does, then read the explanations we have provided to describe what is going on. If you still do not understand, then check out the Django documentation, go to stack overflow, search the web until you have filled this gap in your knowledge.

How To Tango With Django 1.7
(http://www.tangowithdjango.com/book17/)


How to Tango with Django 1.9Azzopardi, L. and Maxwell, D. (2016) How to Tango with Django 1.9 – A beginners guide to Python/Django
(https://leanpub.com/tangowithdjango19)

Download eBook Sample Book PDF (PDF 2,444KB)

The first edition of the Tango with Django book (available at: http://www.tangowithdjango.com) was launched in October 2013 by Leif Azzopardi and David Maxwell, both at the University of Glasgow, Scotland. The book has been used as the course textbook for web development courses within the University, and since its launch we’ve had over half a million visitors. We’re now at the third iteration, with lots of interest from potential readers. )

Tango with Django is a beginner’s guide to web development using the Python programming language and the popular Django framework. The book teaches you the basics through a step-by-step guide, and is written in a clear, friendly way.

Table of Contents

  • Overview
    • 1.1 Why Work with this Book?
    • 1.2 What You will Learn
    • 1.3 Technologies and Services
    • 1.4 Rango: Initial Design and Specification
    • 1.5 Summary
  • 2. Getting Ready to Tango
    • 2.1 Python
    • 2.2 The Python Package Manager
    • 2.3 Virtual Environments
    • 2.4 Integrated Development Environment
    • 2.5 Code Repository
  • 3. Django Basics
    • 3.1 Testing Your Setup
    • 3.2 Creating Your Django Project
    • 3.3 Creating a Django Application
    • 3.4 Creating a View
    • 3.5 Mapping URLs
    • 3.6 Basic Workflows
  • 4. Templates and Static Media
    • 4.1 Using Templates
    • 4.2 Serving Static Media
    • 4.3 Basic Workflow
  • 5. Models and Databases
    • 5.1 Rango’s Requirements
    • 5.2 Telling Django about Your Database
    • 5.3 Creating Models
    • 5.4 Creating and Migrating the Database
    • 5.5 Django Models and the Shell
    • 5.6 Configuring the Admin Interface
    • 5.7 Creating a Population Script
    • 5.8 Workflow: Model Setup
  • 6. Models, Templates and Views
    • 6.1 Workflow: Data Driven Page
    • 6.2 Showing Categories on Rango’s Homepage
    • 6.3 Creating a Details Page
  • 7. Forms
    • 7.1 Basic Workflow
    • 7.2 Page and Category Forms
  • 8. Working with Templates
    • 8.1 Using Relative URLs in Templates
    • 8.2 Dealing with Repetition
    • 8.3 Template Inheritance
    • 8.4 The render() Method and the request Context
    • 8.5 Custom Template Tags
    • 8.6 Summary
  • 9. User Authentication
    • 9.1 Setting up Authentication
    • 9.2 Password Hashing
    • 9.3 Password Validators
    • 9.4 The User Model
    • 9.5 Additional User Attributes
    • 9.6 Creating a User Registration View and Template
    • 9.7 Implementing Login Functionality
    • 9.8 Restricting Access
    • 9.9 Logging Out
    • 9.10 Taking it Further
  • 10. Cookies and Sessions
    • 10.1 Cookies, Cookies Everywhere!
    • 10.2 Sessions and the Stateless Protocol
    • 10.3 Setting up Sessions in Django
    • 10.4 A Cookie Tasting Session
    • 10.5 Client Side Cookies: A Site Counter Example
    • 10.6 Session Data
    • 10.7 Browser-Length and Persistent Sessions
    • 10.8 Clearing the Sessions Database
    • 10.9 Basic Considerations and Workflow
  • 11. User Authentication with Django-Registration-Redux
    • 11.1 Setting up Django Registration Redux
    • 11.2 Functionality and URL mapping
    • 11.3 Setting up the Templates
  • 12. Bootstrapping Rango
    • 12.1 The New Base Template
    • 12.2 Quick Style Change
    • 12.3 Using Django-Bootstrap-Toolkit
  • 13. Bing Search
    • 13.1 The Bing Search API
    • 13.2 Adding Search Functionality
    • 13.3 Putting Search into Rango
  • 14. Work In Progress
  • 15. Making Rango Tango! Exercises
    • 15.1 Track Page Click Throughs
    • 15.2 Searching Within a Category Page
    • 15.3 Create and View Profiles
  • 16. Making Rango Tango! Code and Hints
    • 16.1 Track Page Click Throughs
    • 16.2 Searching Within a Category Page
  • 17. JQuery and Django
    • 17.1 Including JQuery in Your Django Project/Application
    • 17.2 DOM Manipulation Example
  • 18. AJAX in Django with JQuery
    • 18.1 AJAX based Functionality
    • 18.2 Add a “Like Button”
    • 18.3 Adding Inline Category Suggestions
  • 19. Automated Testing
    • 19.1 Running Tests
    • 19.2 Coverage Testing
  • 20. Deploying Your Project
    • 20.1 Creating a PythonAnywhere Account
    • 20.2 The PythonAnywhere Web Interface
    • 20.3 Creating a Virtual Environment
    • 20.4 Setting up Your Web Application
    • 20.5 Log Files
  • 21. A CSS Crash Course
    • 21.1 Including Stylesheets
    • 21.2 Basic CSS Selectors
    • 21.3 Element Selectors
    • 21.4 Fonts
    • 21.5 Colours and Backgrounds
    • 21.6 Containers, Block-Level and Inline Elements
    • 21.7 Basic Positioning
    • 21.8 The Box Model
    • 21.9 Styling Lists
    • 21.10 Styling Links
    • 21.11 The Cascade
    • 21.12 Additional Reading
  • 22. Final Thoughts
  • 23. Setting up your System
    • 23.1 Installing the Software
    • 23.2 Virtual Environments
    • 24. Exercises
  • 25. A Crash Course in UNIX-based Commands
    • 25.1 Using the Terminal
    • 25.2 Core Commands
  • 26. Virtual Environments
  • 27. A Git Crash Course
    • 27.1 Why Use Version Control?
    • 27.2 How Git Works
    • 27.3 Setting up Git
    • 27.4 Basic Commands and Workflow
    • 27.5 Recovering from Mistakes

Image result for full stack pythonFull Stack Python – Django
(https://www.fullstackpython.com/django.html)

Django is a widely-used Python web application framework with a “batteries-included” philosophy. The principle behind batteries-included is that the common functionality for building web applications should come with the framework instead of as separate libraries.

For example, authentication, URL routing, a templating system, an object-relational mapper (ORM), and database schema migrations (as of version 1.7) are all included with the Django framework. Compare that included functionality to the Flask framework which requires a separate library such as Flask-Login to perform user authentication.

The batteries-included and extensibility philosophies are simply two different ways to tackle framework building. Neither philosophy is inherently better than the other one.

Django is an implementation of the web frameworks concept. Learn how these pieces fit together in the web development chapter or view the table of contents for all topics.

Why is Django a good web framework choice?

The Django project’s stability, performance and community have grown tremendously over the past decade since the framework’s creation. Detailed tutorials and good practices are readily available on the web and in books. The framework continues to add significant new functionality such as database migrations with each release.

I highly recommend the Django framework as a starting place for new Python web developers because the official documentation and tutorials are some of the best anywhere in software development.

There’s some debate on whether learning Python by using Django is a bad idea. However, that criticism is invalid if you take the time to learn the Python syntax and language semantics first before diving into web development.

Django books and tutorials

There are a slew of free or low cost resources out there for Django. Since Django was released over 10 years ago and has had a huge number of updates since then, when you’re looking for an up-to-date Django book check out the list below or read this post showing current Django books as of Django 1.8, 1.9.

Django videos

Are you looking for Django videos in addition to articles? There is a special section for Django and web development on the best Python videos page.

Django migrations

  • Paul Hallett wrote a detailed Django 1.7 app upgrade guide on the Twilio blog from his experience working with the django-twilio package.
  • Real Python’s migrations primer explores the difference between South’s migrations and the built-in Django 1.7 migrations as well as how you use them.
  • Andrew Pinkham’s “Upgrading to Django 1.7” series is great learning material for understanding what’s changed in this major release and how to adapt your Django project. Part 1, part 2 and part 3 and part 4 are now all available to read.
  • Django migrations without downtimes shows one potential way of performing on-line schema migrations with Django.

Channels in 1.9+

Channels are a new mechanism in Django 1.9 (as a standalone app, later for incorporation into the core framework in 1.10) for real-time full-duplex communication between the browser and the server based on WebSockets.

Django testing

Django with Angular (Djangular) resources

Django ORM resources

Django comes with its own custom object-relational mapper (ORM) typically referred to as “the Django ORM”. Learn more about the Django ORM on the Python object-relational mappers page that includes a section specifically for the Django ORM as well as additional resources and tutorials.

Static and media files

Deploying and handling static and media files can be confusing for new Django developers. These resources along with the static content page are useful for figuring out how to handle these files properly.

Open source Django example projects

  • Browser calls with Django and Twilio shows how to build a web app with Django and Twilio Client to turn a user’s web browser into a full-fledged phone. Pretty awesome!
  • Txt 2 React is a full Django web app that allows audiences to text in during a presentation with feedback or questions.
  • Openduty is a website status checking and alert system similar to PagerDuty.
  • Courtside is a pick up sports web application written and maintained by the author of PyCoder’s Weekly.
  • These two Django Interactive Voice Response (IVR) system web application repositories part 1 and part 2 show you how to build a really cool Django application. There’s also an accompanying blog post with detailed explanations of each step.
  • Taiga is a project management tool built with Django as the backend and AngularJS as the front end.

Django project templates

Django learning checklist

  1. Install Django on your local development machine.
  2. Work through the initial “polls” tutorial.
  3. Build a few more simple applications using the tutorial resources found in the “Django resources” section.
  4. Start coding your own Django project with help from the official documentation and resource links below. You’ll make plenty of mistakes which is critical on your path to learning the right way to build applications.
  5. Read 2 Scoops of Django to understand Django good practices and learn better ways of building Django web applications.
  6. Move on to the deployment section to get your Django project on the web.

Table of Contents

Introduction

2. Development Environments

3. Programming Language

4. Web Development

5. Web Frameworks

6. Data