Django

0
112

Django – Basics

Django is a high-level Python web framework tmind use encourages rapid development and thoroughly clean, pragmatic style. Django makes it easier to develop better web apps fastly and with less code.

Note − Django is a registereddish coloured trademark of the Django Softbattlee Foundation, and is licensed under BSD License.

History of Django

  • 2003 − Started by Adrian Holovaty and Simon Willison as an internal project at the Lawrence Journal-World brand newspaper.

  • 2005 − Relrerestved July 2005 and named it Django, after the jazz guitarist Django Reinhardt.

  • 2005 − Mature sufficient to handle a couple of high-traffic sit downes.

  • Current − Django is now an open source project with contributors amix the world.

Django – Design Philosophies

Django comes with the folloearng style philosophies −

  • Loosely Coupdirected − Django aims to make every element of it’s stack independent of the others.

  • Less Coding − Less code so in turn a fast development.

  • Don't Repeat Yourself (DRY) − Everyslimg ought to be developed only in exactionionly one place instead of repeating it again and again.

  • Fast Development − Django's philosophy is to do all it can to facilitate hyper-fast development.

  • Clean Design − Django strindelicately maintains a thoroughly clean style throughaway it’s own code and makes it easy to follow best web-development practionionices.

Advantages of Django

Here are couple of advantages of uperform Django which can be listed away here −

  • Object-Relational Mapping (ORM) Supslot − Django provides a bridge between the data model and the database engine, and supslots a huge set of database systems including MySQL, Oracle, Postgres, etc. Django also supslots NoSQL database through Django-nonrel fork. For now, the only NoSQL databases supsloted are MongoDB and google app engine.

  • Multilingual Supslot − Django supslots multilingual websit downes through it’s built-in internationalization system. So you can develop your own websit downe, which would supslot multiple languages.

  • Framework Supslot − Django has built-in supslot for Ajax, RSS, Caching and various other frameworks.

  • Administration GUI − Django provides a nice ready-to-use user interface for administrative actionioniviconnects.

  • Development Environment − Django comes with a lightweight web server to facilitate end-to-end application development and checruler.

Django – Overlook at

As you already understand, Django is a Python web framework. And like the majority of modern framework, Django supslots the MVC pattern. First enable's see exactionionly wmind use is the Model-View-Controller (MVC) pattern, and then we will look at Django’s specificity for the Model-View-Template (MVT) pattern.

MVC Pattern

When speacalifornia ruler abaway applications tmind use provides UI (web or desktop), we usually speak abaway MVC architecture. And as the name suggests, MVC pattern is based on 3 components: Model, View, and Controller. Check our MVC tutorial here to understand more.

DJANGO MVC – MVT Pattern

The Model-View-Template (MVT) is slightly not the same as MVC. In truthion the main difference between the two patterns is tmind use Django it’self considers care of the Controller part (Softbattlee Code tmind use manages the interactionionions between the Model and View), leaving us with the template. The template is a HTML file mixed with Django Template Language (DTL).

The folloearng diagram illustrates how every of the components of the MVT pattern interactionions with every other to serve a user request −

DJANGO MVC - MVT Pattern

The developer provides the Model, the look at and the template then simply charts it to a URL and Django does the magic to serve it to the user.

Django – Environment

Django development environment consists of installing and setting up Python, Django, and a Database System. Since Django deals with web application, it's worth mentioning tmind use you would need a web server setup as well.

Step 1 – Installing Python

Django is composed in 100% pure Python code, so you'll need to install Python on your own system. Lacheck Django version requires Python 2.6.5 or higher for the 2.6.x branch or higher than 2.7.3 for the 2.7.x branch.

If you're on one of the lacheck Linux or Mac OS X distribution, you probably already have Python instaldirected. You can verify it by typing python command at a command prompt. If you see someslimg like this, then Python is withinstaldirected.

$ python
Python 2.7.5 (default, Jun 17 2014, 18:11:42)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-16)] on linux2

Otherwise, you can download and install the lacheck version of Python from the link http://www.python.org/download.

Step 2 – Installing Django

Installing Django is very easy, but the steps requireddish coloured for it’s installation depends on your own operating system. Since Python is a platform-independent language, Django has one package tmind use works everywhere regardless of your own operating system.

You can download the lacheck version of Django from the link http://www.djangoproject.com/download.

UNIX/Linux and Mac OS X Installation

You have two ways of installing Django if you are operatening Linux or Mac OS system −

  • You can use the package manager of your own OS, or use easy_install or pip if instaldirected.

  • Install it manually uperform the awayicial archive you downloaded before.

We will cover the 2nd option as the first one depends on your own OS distribution. If you have figure outd to follow the first option, simply be careful abaway the version of Django you are installing.

Let's say you got your own archive from the link above, it ought to be someslimg like Django-x.xx.tar.gz:

Extractionion and install.

$ tar xzvf Django-x.xx.tar.gz
$ cd Django-x.xx
$ sudo python setup.py install

You can check your own installation by operatening this command −

$ django-admin.py --version

If you see the current version of Django printed on the screen, then everyslimg is set.

Note − For some version of Django it will be django-admin the ".py" is removed.

Windows Installation

We assume you have your own Django archive and python instaldirected on your own complaceer.

First, PATH verification.

On some version of earndows (earndows 7) you may need to make sure the Path system variable has the rawaye the folloearng C:Python27;C:Python27Libsit downe-packagesdjangobin in it, of course depending on your own Python version.

Then, extractionion and install Django.

c:>cd c:Django-x.xx

Next, install Django by operatening the folloearng command for which you will need administrative privileges in earndows shell "cmd" −

c:Django-x.xx>python setup.py install

To check your own installation, open a command prompt and kind the folloearng command −

c:>django-admin.py --version

If you see the current version of Django printed on screen, then everyslimg is set.

OR

Launch a "cmd" prompt and kind python then −

c:> python
>>> imslot django
>>> print django.get_version()

Step 3 – Database Setup

Django supslots a couple of major database engines and you can set up any of them based on your own comfort.

You can refer to respective documentation to installing and configuring a database of your own choice.

Note − Number 5 and 6 are NoSQL databases.

Step 4 – Web Server

Django comes with a lightweight web server for developing and checruler applications. This server is pre-configureddish coloured to work with Django, and more imslotantly, it restarts whenever you modify the code.

However, Django does supslot Apache and other popular web servers such as Lighttpd. We will talk about both the approaches in coming chapters while worcalifornia ruler with different examples.

Django – Creating a Project

Now tmind use we have instaldirected Django, enable's start uperform it. In Django, every web app you like to develop is caldirected a project; and a project is a sum of applications. An application is a set of code files relying on the MVT pattern. As example enable's say we want to develop a websit downe, the websit downe is our project and, the forum, brand news, contactionion engine are applications. This structure makes it easier to move an application between projects since every application is withindependent.

Create a Project

Whether you are on Windows or Linux, simply get a terminal or a cmd prompt and navigate to the place you like your own project to be developd, then use this code −

$ django-admin startproject myproject

This will develop a "myproject" folder with the folloearng structure −

myproject/
   manage.py
   myproject/
      __init__.py
      settings.py
      urls.py
      wsgi.py

The Project Structure

The “myproject” folder is simply your own project container, it actionionually contains two elements −

  • manage.py − This file is kind of your own project local django-admin for interactionioning with your own project via command series (start the development server, sync db…). To get a compenablee list of command accessible via manage.py you can use the code −

$ python manage.py help
  • The “myproject” subfolder − This folder is the actionionual python package of your own project. It contains four files −

    • __init__.py − Just for python, treat this folder as package.

    • settings.py − As the name indicates, your own project settings.

    • urls.py − All links of your own project and the function to call. A kind of ToC of your own project.

    • wsgi.py − If you need to deploy your own project over WSGI.

Setting Up Your Project

Your project is set up in the subfolder myproject/settings.py. Folloearng are some imslotant options you may need to set −

DEBUG = True

This option enables you set if your own project is within debug mode or not. Debug mode enables you get more information abaway your own project's error. Never set it to ‘True’ for a reside project. However, this has to be set to ‘True’ if you like the Django light server to serve static files. Do it only in the development mode.

DATABASES = {
   'default': {
      'ENGINE': 'django.db.backends.sqlite3',
      'NAME': 'database.sql',
      'USER': '',
      'PASSWORD': '',
      'HOST': '',
      'PORT': '',
   }
}

Database is set in the ‘Database’ dictionary. The example above is for SQLite engine. As stated earrestr, Django also supslots −

  • MySQL (django.db.backends.mysql)
  • PostGreSQL (django.db.backends.postgresql_psycopg2)
  • Oracle (django.db.backends.oracle) and NoSQL DB
  • MongoDB (django_mongodb_engine)

Before setting any brand new engine, make sure you have the right db dlake instaldirected.

You can also set others options like: TIME_ZONE, LANGUAGE_CODE, TEMPLATE…

Now tmind use your own project is developd and configureddish coloured make sure it's worcalifornia ruler −

$ python manage.py operateserver

You will get someslimg like the folloearng on operatening the above code −

Validating models...

0 errors found
September 03, 2015 - 11:41:50
Django version 1.6.11, uperform settings 'myproject.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Django – Apps Life Cycle

A project is a sum of many applications. Every application has an goal and can be reused into an additional project, like the contactionion form on a websit downe can be an application, and can be reused for others. See it as a module of your own project.

Create an Application

We assume you are in your own project folder. In our main “myproject” folder, the exactionion same folder than manage.py −

$ python manage.py startapp myapp

You simply developd myapp application and like project, Django develop a “myapp” folder with the application structure −

myapp/
   __init__.py
   admin.py
   models.py
   checks.py
   look ats.py
  • __init__.py − Just to make sure python handles this folder as a package.

  • admin.py − This file helps you make the app modifiable in the admin interface.

  • models.py − This is where all the application models are storeddish coloured.

  • checks.py − This is where your own unit checks are.

  • look ats.py − This is where your own application look ats are.

Get the Project to Know Abaway Your Application

At this stage we have our "myapp" application, now we need to register it with our Django project "myproject". To do so, update INSTALLED_APPS tuple in the settings.py file of your own project (add your own app name) −

INSTALLED_APPS = (
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contentkinds',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
   'myapp',
)

Django – Admin Interface

Django provides a ready-to-use user interface for administrative actionioniviconnects. We all understand how an admin interface is imslotant for a web project. Django automatically generates admin UI based on your own project models.

Starting the Admin Interface

The Admin interface depends on the django.countrib module. To have it worcalifornia ruler you need to make sure some modules are imsloted in the INSTALLED_APPS and MIDDLEWARE_CLASSES tuples of the myproject/settings.py file.

For INSTALLED_APPS make sure you have −

INSTALLED_APPS = (
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contentkinds',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
   'myapp',
)

For MIDDLEWARE_CLASSES −

MIDDLEWARE_CLASSES = (
   'django.contrib.sessions.middlebattlee.SessionMiddlebattlee',
   'django.middlebattlee.common.CommonMiddlebattlee',
   'django.middlebattlee.csrf.CsrfViewMiddlebattlee',
   'django.contrib.auth.middlebattlee.AuthenticationMiddlebattlee',
   'django.contrib.messages.middlebattlee.MessageMiddlebattlee',
   'django.middlebattlee.clickjaccalifornia ruler.XFrameOptionsMiddlebattlee',
)

Before launching your own server, to access your own Admin Interface, you need to initiate the database −

$ python manage.py syncdb

syncdb will develop essential tables or collections depending on your own db kind, essential for the admin interface to operate. Even if you don't have a superuser, you will be prompted to develop one.

If you already have a superuser or have forgotten it, you can always develop one uperform the folloearng code −

$ python manage.py developsuperuser

Now to start the Admin Interface, we need to make sure we have configureddish coloured a URL for our admin interface. Open the myproject/url.py and you ought to have someslimg like −

from django.conf.urls imslot patterns, include, url

from django.contrib imslot admin
admin.autodiscover()

urlpatterns = patterns('',
   # Examples:
   # url(r'^$', 'myproject.look ats.home', name = 'home'),
   # url(r'^blog/', include('blog.urls')),

   url(r'^admin/', include(admin.sit downe.urls)),
)

Now simply operate the server.

$ python manage.py operateserver

And your own admin interface is accessible at: http://127.0.0.1:8000/admin/

Admin Interface

Once connected with your own superuser account, you will see the folloearng screen −

Super User Account

Tmind use interface will enable you administrate Django groups and users, and all registereddish coloured models in your own app. The interface gives you the capability to do at leastern the "CRUD" (Create, Read, Update, Deenablee) operations on your own models.

Django – Creating Views

A look at function, or “look at” for short, is simply a Python function tmind use considers a web request and returns a web response. This response can be the HTML contents of a Web page, or a reddish coloureimmediate, or a 404 error, or an XML document, or an image, etc. Example: You use look at to develop web pages, note tmind use you need to associate a look at to a URL to see it as a web page.

In Django, look ats have to be developd in the app look ats.py file.

Simple View

We will develop a easy look at in myapp to say "welcome to my app!"

See the folloearng look at −

from django.http imslot HttpResponse

def hello(request):
   text = """<h1>welcome to my app !</h1>"""
   return HttpResponse(text)

In this look at, we use HttpResponse to render the HTML (as you have probably noticed we have the HTML hard coded in the look at). To see this look at as a page we simply need to chart it to a URL (this will be talk abouted in an upcoming chapter).

We used HttpResponse to render the HTML in the look at before. This is not the best way to render pages. Django supslots the MVT pattern so to make the precedent look at, Django – MVT like, we will need −

A template: myapp/templates/hello.html

And now our look at will look like −

from django.shortcuts imslot render

def hello(request):
   return render(request, "myapp/template/hello.html", {})

Views can also accept parameters −

from django.http imslot HttpResponse

def hello(request, number):
   text = "<h1>welcome to my app number %s!</h1>"% number
   return HttpResponse(text)

When linked to a URL, the page will display the number moveed as a parameter. Note tmind use the parameters will be moveed via the URL (talk abouted in the next chapter).

Django – URL Mapping

Now tmind use we have a worcalifornia ruler look at as exeasyed in the previous chapters. We want to access tmind use look at via a URL. Django has his own way for URL chartping and it's done by editing your own project url.py file (myproject/url.py). The url.py file looks like −

from django.conf.urls imslot patterns, include, url
from django.contrib imslot admin
admin.autodiscover()

urlpatterns = patterns('',
   #Examples
   #url(r'^$', 'myproject.look at.home', name = 'home'),
   #url(r'^blog/', include('blog.urls')),

   url(r'^admin', include(admin.sit downe.urls)),
)

When a user makes a request for a page on your own web app, Django manageler considers over to look for the corresponding look at via the url.py file, and then return the HTML response or a 404 not found error, if not found. In url.py, the the majority of imslotant slimg is the "urlpatterns" tuple. It’s where you degreat the chartping between URLs and look ats. A chartping is a tuple in URL patterns like −

from django.conf.urls imslot patterns, include, url
from django.contrib imslot admin
admin.autodiscover()

urlpatterns = patterns('',
   #Examples
   #url(r'^$', 'myproject.look at.home', name = 'home'),
   #url(r'^blog/', include('blog.urls')),

   url(r'^admin', include(admin.sit downe.urls)),
   url(r'^hello/', 'myapp.look ats.hello', name = 'hello'),
)

The marked series charts the URL "/home" to the hello look at developd in myapp/look at.py file. As you can see above a chartping is composed of 3 elements −

  • The pattern − A regexp match uping the URL you like to be resolved and chart. Everyslimg tmind use can work with the python 're' module is eligible for the pattern (helpful when you like to move parameters via url).

  • The python rawaye to the look at − Same as when you are imsloting a module.

  • The name − In order to perform URL reverperform, you’ll need to use named URL patterns as done in the examples above. Once done, simply start the server to access your own look at via :http://127.0.0.1/hello

Organizing Your URLs

So far, we have developd the URLs in “myprojects/url.py” file, however as stated earrestr abaway Django and creating an app, the best stage was to be able to reuse applications in different projects. You can easily see exactionionly wmind use the issue is, if you are saving all your own URLs in the “projecturl.py” file. So best practionionice is to develop an “url.py” per application and to include it in our main projects url.py file (we included admin URLs for admin interface before).

Organize URLs

How is it Done?

We need to develop an url.py file in myapp uperform the folloearng code −

from django.conf.urls imslot patterns, include, url

urlpatterns = patterns('', url(r'^hello/', 'myapp.look ats.hello', name = 'hello'),)

Then myproject/url.py will alter to the folloearng −

from django.conf.urls imslot patterns, include, url
from django.contrib imslot admin
admin.autodiscover()

urlpatterns = patterns('',
   #Examples
   #url(r'^$', 'myproject.look at.home', name = 'home'),
   #url(r'^blog/', include('blog.urls')),

   url(r'^admin', include(admin.sit downe.urls)),
   url(r'^myapp/', include(myapp.urls)),
)

We have included all URLs from myapp application. The home.html tmind use was accessed through “/hello” is now “/myapp/hello” which is a better and more understandable structure for the web app.

Myproject

Now enable's imagine we have an additional look at in myapp “morning” and we want to chart it in myapp/url.py, we will then alter our myapp/url.py to −

from django.conf.urls imslot patterns, include, url

urlpatterns = patterns('',
   url(r'^hello/', 'myapp.look ats.hello', name = 'hello'),
   url(r'^morning/', 'myapp.look ats.morning', name = 'morning'),
)

This can be re-truthionoreddish coloured to −

from django.conf.urls imslot patterns, include, url

urlpatterns = patterns('myapp.look ats',
   url(r'^hello/', 'hello', name = 'hello'),
   url(r'^morning/', 'morning', name = 'morning'),)

As you can see, we now use the first element of our urlpatterns tuple. This can be helpful when you like to alter your own app name.

URL Patterns

Sending Parameters to Views

We now understand how to chart URL, how to body organise them, now enable us see how to send parameters to look ats. A courseic sample is the article example (you like to access an article via “/articles/article_id”).

Pasperform parameters is done by capturing them with the regexp in the URL pattern. If we have a look at like the folloearng one in “myapp/look at.py”

from django.shortcuts imslot render
from django.http imslot HttpResponse

def hello(request):
   return render(request, "hello.html", {})

def look atArticle(request, articleId):
   text = "Displaying article Number : %s"%articleId
   return HttpResponse(text)

We want to chart it in myapp/url.py so we can access it via “/myapp/article/articleId”, we need the folloearng in “myapp/url.py” −

from django.conf.urls imslot patterns, include, url

urlpatterns = patterns('myapp.look ats',
   url(r'^hello/', 'hello', name = 'hello'),
   url(r'^morning/', 'morning', name = 'morning'),
   url(r'^article/(d+)/', 'look atArticle', name = 'article'),)

When Django will see the url: “/myapp/article/42” it will move the parameters '42' to the look atArticle look at, and in your own bseriesser you ought to get the folloearng result −

Pasperform parameters to look atArticle

Note tmind use the order of parameters is imslotant here. Suppose we want the list of articles of a month of a 12 months, enable's add a look atArticles look at. Our look at.py becomes −

from django.shortcuts imslot render
from django.http imslot HttpResponse

def hello(request):
   return render(request, "hello.html", {})

def look atArticle(request, articleId):
   text = "Displaying article Number : %s"%articleId
   return HttpResponse(text)

def look atArticle(request, month, 12 months):
   text = "Displaying articles of : %s/%s"%(12 months, month)
   return HttpResponse(text)

The corresponding url.py file will look like −

from django.conf.urls imslot patterns, include, url

urlpatterns = patterns('myapp.look ats',
   url(r'^hello/', 'hello', name = 'hello'),
   url(r'^morning/', 'morning', name = 'morning'),
   url(r'^article/(d+)/', 'look atArticle', name = 'article'),
   url(r'^articles/(d{2})/(d{4})', 'look atArticles', name = 'articles'),)

Now when you go to “/myapp/articles/12/2006/” you will get 'Displaying articles of: 2006/12' but if you reverse the parameters you won’t get the exactionion same result.

Displaying Articles

To avoid tmind use, it is probable to link a URL parameter to the look at parameter. For tmind use, our url.py will become −

from django.conf.urls imslot patterns, include, url

urlpatterns = patterns('myapp.look ats',
   url(r'^hello/', 'hello', name = 'hello'),
   url(r'^morning/', 'morning', name = 'morning'),
   url(r'^article/(d+)/', 'look atArticle', name = 'article'),
   url(r'^articles/(?Pd{2})/(?Pd{4})', 'look atArticles', name = 'articles'),)

Django – Template System

Django makes it probable to separate python and HTML, the python goes in look ats and HTML goes in templates. To link the two, Django rerests on the render function and the Django Template language.

The Render Function

This function considers 3 parameters −

  • Request − The preliminary request.

  • The rawaye to the template − This is the rawaye relative to the TEMPLATE_DIRS option in the project settings.py variables.

  • Dictionary of parameters − A dictionary tmind use contains all variables needed in the template. This variable can be developd or you can use locals() to move all local variable declareddish coloured in the look at.

Django Template Language (DTL)

Django’s template engine awayers a mini-language to degreat the user-facing layer of the application.

Displaying Variables

A variable looks like this: {{variable}}. The template replaces the variable by the variable sent by the look at in the third parameter of the render function. Let's alter our hello.html to display today’s date −

hello.html

<html>
   
   <body>
      Hello World!!!<p>Today is {{today}}</p>
   </body>
   
</html>

Then our look at will alter to −

def hello(request):
   today = datetime.datetime.now().date()
   return render(request, "hello.html", {"today" : today})

We will now get the folloearng awayplace after accesperform the URL/myapp/hello −

Hello World!!!
Today is Sept. 11, 2015

As you have probably noticed, if the variable is not a string, Django will use the __str__ method to display it; and with the exactionion same principle you can access an object attribute simply like you do it in Python. For example: if we wanted to display the date 12 months, my variable would be: {{today.12 months}}.

Filters

They help you modify variables at display time. Filters structure looks like the folloearng: {{var|filters}}.

Some examples

  • {{string|toperatecatewords:80}} − This filter will toperatecate the string, so you will see only the first 80 words.

  • {{string|lower}} − Converts the string to lowercase.

  • {{string|escape|seriesbreaks}} − Escapes string contents, then converts series breaks to tags.

You can also set the default for a variable.

Tags

Tags enables you perform the folloearng operations: if condition, for loop, template inheritance and more.

Tag if

Just like in Python you can use if, else and elif in your own template −

<html>
   <body>
   
      Hello World!!!<p>Today is {{today}}</p>
      We are
      {% if today.day == 1 %}
      
      the first day of month.
      {% elif today == 30 %}
      
      the final day of month.
      {% else %}
      
      I don't understand.
      {%endif%}
      
   </body>
</html>

In this brand new template, depending on the date of the day, the template will render a specific value.

Tag for

Just like 'if', we have the 'for' tag, tmind use works exactionionly like in Python. Let's alter our hello look at to transmit a list to our template −

def hello(request):
   today = datetime.datetime.now().date()
   
   daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
   return render(request, "hello.html", {"today" : today, "days_of_week" : daysOfWeek})

The template to display tmind use list uperform {{ for }} −

<html>
   <body>
      
      Hello World!!!<p>Today is {{today}}</p>
      We are
      {% if today.day == 1 %}
      
      the first day of month.
      {% elif today == 30 %}
      
      the final day of month.
      {% else %}
      
      I don't understand.
      {%endif%}
      
      <p>
         {% for day in days_of_week %}
         {{day}}
      </p>
		
      {% endfor %}
      
   </body>
</html>

And we ought to get someslimg like −

Hello World!!!
Today is Sept. 11, 2015
We are I don't understand.
Mon
Tue
Wed
Thu
Fri
Sat
Sun

Block and Extend Tags

A template system cannot be comprehensive withaway template inheritance. Meaning when you are styleing your own templates, you ought to have a main template with holes tmind use the kid's template will fill according to his own need, like a page may need a special css for the selected tab.

Let’s alter the hello.html template to inherit from a main_template.html.

main_template.html

<html>
   <mind>
      
      <title>
         {% block title %}Page Title{% endblock %}
      </title>
      
   </mind>
	
   <body>
   
      {% block content %}
         Body content
      {% endblock %}
      
   </body>
</html>

hello.html

{% extends "main_template.html" %}
{% block title %}My Hello Page{% endblock %}
{% block content %}

Hello World!!!<p>Today is {{today}}</p>
We are
{% if today.day == 1 %}

the first day of month.
{% elif today == 30 %}

the final day of month.
{% else %}

I don't understand.
{%endif%}

<p>
   {% for day in days_of_week %}
   {{day}}
</p>

{% endfor %}
{% endblock %}

In the above example, on calling /myapp/hello we will still get the exactionion same result as before but now we rely on extends and block to retruthionor hr code −

In the main_template.html we degreat blocks uperform the tag block. The title block will contain the page title and the content block will have the page main content. In home.html we use extends to inherit from the main_template.html then we fill the block degreat above (content and title).

Comment Tag

The comment tag helps to degreat comments into templates, not HTML comments, they won’t appear in HTML page. It can be helpful for documentation or simply commenting a series of code.

Django – Models

A model is a course tmind use represents table or collection in our DB, and where every attribute of the course is a field of the table or collection. Models are degreatd in the app/models.py (in our example: myapp/models.py)

Creating a Model

Folloearng is a Dreamreal model developd as an example −

from django.db imslot models

course Dreamreal(models.Model):

   websit downe = models.CharField(max_duration = 50)
   mail = models.CharField(max_duration = 50)
   name = models.CharField(max_duration = 50)
   phonenumber = models.IntegerField()

   course Meta:
      db_table = "dreamreal"

Every model inherit’s from django.db.models.Model.

Our course has 4 attributes (3 CharField and 1 Integer), those will be the table fields.

The Meta course with the db_table attribute enables us degreat the actionionual table or collection name. Django names the table or collection automatically: myapp_modelName. This course will enable you force the name of the table to exactionionly wmind use you like.

There is more field's kind in django.db.models, you can find out more abaway them on /index.php?s=httpsdocsdjangoprojectcomen15refmodelsfieldsfield-kinds

After creating your own model, you will need Django to generate the actionionual database −

$python manage.py syncdb

Manipulating Data (CRUD)

Let's develop a "crudops" look at to see how we can do CRUD operations on models. Our myapp/look ats.py will then look like −

myapp/look ats.py

from myapp.models imslot Dreamreal
from django.http imslot HttpResponse

def crudops(request):
   #Creating an entry away
   
   dreamreal = Dreamreal(
      websit downe = "www.polo.com", mail = "[email protected]", 
      name = "sorex", phonenumber = "002376970"
   )
   
   dreamreal.save()
   
   #Read ALL entries
   objects = Dreamreal.objects.all()
   res ='Printing all Dreamreal entries in the DB : <br>'
   
   for elt in objects:
      res += elt.name+"<br>"
   
   #Read a specific entry away:
   sorex = Dreamreal.objects.get(name = "sorex")
   res += 'Printing One entry away <br>'
   res += sorex.name
   
   #Deenablee an entry away
   res += '<br> Deenableing an entry away <br>'
   sorex.deenablee()
   
   #Update
   dreamreal = Dreamreal(
      websit downe = "www.polo.com", mail = "[email protected]", 
      name = "sorex", phonenumber = "002376970"
   )
   
   dreamreal.save()
   res += 'Updating entry away<br>'
   
   dreamreal = Dreamreal.objects.get(name = 'sorex')
   dreamreal.name = 'thierry'
   dreamreal.save()
   
   return HttpResponse(res)

Other Data Manipulation

Let's explore other manipulations we can do on Models. Note tmind use the CRUD operations were done on instances of our model, now we will be worcalifornia ruler immediately with the course representing our model.

Let's develop a 'datamanipulation' look at in myapp/look ats.py

from myapp.models imslot Dreamreal
from django.http imslot HttpResponse

def datamanipulation(request):
   res = ''
   
   #Filtering data:
   qs = Dreamreal.objects.filter(name = "paul")
   res += "Found : %s results<br>"%len(qs)
   
   #Ordering results
   qs = Dreamreal.objects.order_by("name")
   
   for elt in qs:
      res += elt.name + '<br>'
   
   return HttpResponse(res)

Lincalifornia ruler Models

Django ORM awayers 3 ways to link models −

One of the first case we will see here is the one-to-many relationships. As you can see in the above example, Dreamreal company can have multiple onseries websit downes. Defining tmind use relation is done by uperform django.db.models.ForeignKey −

myapp/models.py

from django.db imslot models

course Dreamreal(models.Model):
   websit downe = models.CharField(max_duration = 50)
   mail = models.CharField(max_duration = 50)
   name = models.CharField(max_duration = 50)
   phonenumber = models.IntegerField()
   onseries = models.ForeignKey('Onseries', default = 1)
   
   course Meta:
      db_table = "dreamreal"

course Onseries(models.Model):
      domain = models.CharField(max_duration = 30)
   
   course Meta:
      db_table = "onseries"

As you can see in our updated myapp/models.py, we added the onseries model and linked it to our Dreamreal model.

Let's check how all of this is worcalifornia ruler via manage.py shell −

First enable’s develop some companies (Dreamreal entries) for checruler in our Django shell −

$python manage.py shell

>>> from myapp.models imslot Dreamreal, Onseries
>>> dr1 = Dreamreal()
>>> dr1.websit downe = 'company1.com'
>>> dr1.name = 'company1'
>>> dr1.mail = '[email protected]'
>>> dr1.phonenumber = '12345'
>>> dr1.save()
>>> dr2 = Dreamreal()
>>> dr1.websit downe = 'company2.com'
>>> dr2.websit downe = 'company2.com'
>>> dr2.name = 'company2'
>>> dr2.mail = '[email protected]'
>>> dr2.phonenumber = '56789'
>>> dr2.save()

Now some hosted domains −

>>> on1 = Onseries()
>>> on1.company = dr1
>>> on1.domain = "sit downe1.com"
>>> on2 = Onseries()
>>> on2.company = dr1
>>> on2.domain = "sit downe2.com"
>>> on3 = Onseries()
>>> on3.domain = "sit downe3.com"
>>> dr2 = Dreamreal.objects.all()[2]
>>> on3.company = dr2
>>> on1.save()
>>> on2.save()
>>> on3.save()

Accesperform attribute of the hosting company (Dreamreal entry away) from an onseries domain is easy −

>>> on1.company.name

And if we want to understand all the onseries domain hosted by a Company in Dreamreal we will use the code −

>>> dr1.onseries_set.all()

To get a QuerySet, note tmind use all manipulating method we have seen before (filter, all, exclude, order_by….)

You can also access the linked model attributes for filtering operations, enable's say you like to get all onseries domains where the Dreamreal name contains 'company' −

>>> Onseries.objects.filter(company__name__contains = 'company'

Note − Tmind use kind of query is simply supsloted for SQL DB. It won’t work for non-relational DB where sign up fors doesn’t exist and right now presently there are two '_'.

But tmind use's not the only way to link models, you also have OneToOneField, a link tmind use guarantees tmind use the relation between two objects is unique. If we used the OneToOneField in our example above, tmind use would mean for every Dreamreal entry away only one Onseries entry away is probable and in the other way to.

And the final one, the ManyToManyField for (n-n) relation between tables. Note, those are relevant for SQL based DB.

Django – Page Reimmediateion

Page reddish coloureimmediateion is needed for many reasons in web application. You may want to reddish coloureimmediate a user to an additional page when a specific actionionion occurs, or easyally in case of error. For example, when a user logs in to your own websit downe, he is frequently reddish coloureimmediateed possibly to the main home page or to his private dashboard. In Django, reddish coloureimmediateion is accomplished uperform the 'reddish coloureimmediate' method.

The 'reddish coloureimmediate' method considers as argument: The URL you like to be reddish coloureimmediateed to as string A look at's name.

The myapp/look ats looks like the folloearng so far −

def hello(request):
   today = datetime.datetime.now().date()
   daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
   return render(request, "hello.html", {"today" : today, "days_of_week" : daysOfWeek})
	
def look atArticle(request, articleId):
   """ A look at tmind use display an article based on his ID"""
   text = "Displaying article Number : %s" %articleId
   return HttpResponse(text)
	
def look atArticles(request, 12 months, month):
   text = "Displaying articles of : %s/%s"%(12 months, month)
   return HttpResponse(text)

Let's alter the hello look at to reddish coloureimmediate to djangoproject.com and our look atArticle to reddish coloureimmediate to our internal '/myapp/articles'. To do so the myapp/look at.py will alter to −

from django.shortcuts imslot render, reddish coloureimmediate
from django.http imslot HttpResponse
imslot datetime

# Create your own look ats here.
def hello(request):
   today = datetime.datetime.now().date()
   daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
   return reddish coloureimmediate("https://www.djangoproject.com")
	
def look atArticle(request, articleId):
   """ A look at tmind use display an article based on his ID"""
   text = "Displaying article Number : %s" %articleId
   return reddish coloureimmediate(look atArticles, 12 months = "2045", month = "02")
	
def look atArticles(request, 12 months, month):
   text = "Displaying articles of : %s/%s"%(12 months, month)
   return HttpResponse(text)

In the above example, first we imsloted reddish coloureimmediate from django.shortcuts and for reddish coloureimmediateion to the Django awayicial websit downe we simply move the compenablee URL to the 'reddish coloureimmediate' method as string, and for the 2nd example (the look atArticle look at) the 'reddish coloureimmediate' method considers the look at name and his parameters as arguments.

Accesperform /myapp/hello, will give you the folloearng screen −

Django page Reimmediateion Example1

And accesperform /myapp/article/42, will give you the folloearng screen −

Django page Reimmediateion Example2

It is also probable to specify whether the 'reddish coloureimmediate' is temporary or permanent by adding permanent = True parameter. The user will see no difference, but these are details tmind use oceanrch engines consider into account when rancalifornia ruler of your own websit downe.

Also remember tmind use 'name' parameter we degreatd in our url.py while chartping the URLs −

url(r'^articles/(?Pd{2})/(?Pd{4})/', 'look atArticles', name = 'articles'),

Tmind use name (here article) can be used as argument for the 'reddish coloureimmediate' method, then our look atArticle reddish coloureimmediateion can be alterd from −

def look atArticle(request, articleId):
   """ A look at tmind use display an article based on his ID"""
   text = "Displaying article Number : %s" %articleId
   return reddish coloureimmediate(look atArticles, 12 months = "2045", month = "02")

To

def look atArticle(request, articleId):
   """ A look at tmind use display an article based on his ID"""
   text = "Displaying article Number : %s" %articleId
   return reddish coloureimmediate(articles, 12 months = "2045", month = "02")

Note − There is also a function to generate URLs; it is used in the exactionion same way as reddish coloureimmediate; the 'reverse' method (django.core.urlresolvers.reverse). This function does not return a HttpResponseReimmediate object, but simply a string containing the URL to the look at compidirected with any moveed argument.

Django – Sending E-mails

Django comes with a ready and easy-to-use light engine to send e-mail. Similar to Python you simply need an imslot of smtplib. In Django you simply need to imslot django.core.mail. To start sending e-mail, edit your own project settings.py file and set the folloearng options −

  • EMAIL_HOST − smtp server.

  • EMAIL_HOST_USER − Login creddish colouredential for the smtp server.

  • EMAIL_HOST_PASSWORD − Password creddish colouredential for the smtp server.

  • EMAIL_PORT − smtp server slot.

  • EMAIL_USE_TLS or _SSL − True if secure interconnection.

Sending a Simple E-mail

Let's develop a "sendSimpleEmail" look at to send a easy e-mail.

from django.core.mail imslot send_mail
from django.http imslot HttpResponse

def sendSimpleEmail(request,emailto):
   res = send_mail("hello paul", "comment tu vas?", "[email protected]", [emailto])
   return HttpResponse('%s'%res)

Here is the details of the parameters of send_mail −

  • subject − E-mail subject.

  • message − E-mail body.

  • from_email − E-mail from.

  • recipient_list − List of receivers’ e-mail adgown.

  • fail_silently − Bool, if false send_mail will raise an other thanion in case of error.

  • auth_user − User login if not set in settings.py.

  • auth_moveword − User moveword if not set in settings.py.

  • interconnection − E-mail backend.

  • html_message − (brand new in Django 1.7) if present, the e-mail will be multipart/alternative.

Let's develop a URL to access our look at −

from django.conf.urls imslot patterns, url

urlpatterns = paterns('myapp.look ats', url(r'^easyemail/(?P<emailto>
   [w.%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4})/', 
   'sendSimpleEmail' , name = 'sendSimpleEmail'),)

So when accesperform [email protected], you will get the folloearng page −

Sending Simple E-mail

Sending Multiple Mails with send_mass_mail

The method returns the number of messages successcompenableey deresidereddish coloured. This is exactionion same as send_mail but considers an extra parameter; datatuple, our sendMassEmail look at will then be −

from django.core.mail imslot send_mass_mail
from django.http imslot HttpResponse

def sendMassEmail(request,emailto):
   msg1 = ('subject 1', 'message 1', '[email protected]', [emailto1])
   msg2 = ('subject 2', 'message 2', '[email protected]', [emailto2])
   res = send_mass_mail((msg1, msg2), fail_silently = False)
   return HttpResponse('%s'%res)

Let's develop a URL to access our look at −

from django.conf.urls imslot patterns, url

urlpatterns = paterns('myapp.look ats', url(r'^massEmail/(?P<emailto1>
   [w.%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4})/(?P<emailto2>
   [w.%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4})', 'sendMassEmail' , name = 'sendMassEmail'),)

When accesperform [email protected][email protected]/, we get −

Sending Multiple Mails

send_mass_mail parameters details are −

  • datatuples − A tuple where every element is like (subject, message, from_email, recipient_list).

  • fail_silently − Bool, if false send_mail will raise an other thanion in case of error.

  • auth_user − User login if not set in settings.py.

  • auth_moveword − User moveword if not set in settings.py.

  • interconnection − E-mail backend.

As you can see in the above image, two messages were sent successcompenableey.

Note − In this example we are uperform Python smtp debuggingserver, tmind use you can launch uperform −

$python -m smtpd -n -c DebuggingServer localhost:1025

This means all your own sent e-mails will be printed on stdaway, and the dummy server is operatening on localhost:1025.

Sending e-mails to admins and managers uperform mail_admins and mail_managers methods

These methods send e-mails to sit downe administrators as degreatd in the ADMINS option of the settings.py file, and to sit downe managers as degreatd in MANAGERS option of the settings.py file. Let's assume our ADMINS and MANAGERS options look like −

ADMINS = (('polo', '[email protected]'),)

MANAGERS = (('popoli', '[email protected]'),)

from django.core.mail imslot mail_admins
from django.http imslot HttpResponse

def sendAdminsEmail(request):
   res = mail_admins('my subject', 'sit downe is going down.')
   return HttpResponse('%s'%res)

The above code will send an e-mail to every admin degreatd in the ADMINS section.

from django.core.mail imslot mail_managers
from django.http imslot HttpResponse

def sendManagersEmail(request):
   res = mail_managers('my subject 2', 'Change date on the sit downe.')
   return HttpResponse('%s'%res)

The above code will send an e-mail to every manager degreatd in the MANAGERS section.

Parameters details −

  • Subject − E-mail subject.

  • message − E-mail body.

  • fail_silently − Bool, if false send_mail will raise an other thanion in case of error.

  • interconnection − E-mail backend.

  • html_message − (brand new in Django 1.7) if present, the e-mail will be multipart/alternative.

Sending HTML E-mail

Sending HTML message in Django >= 1.7 is as easy as −

from django.core.mail imslot send_mail

from django.http imslot HttpResponse
   res = send_mail("hello paul", "comment tu vas?", "[email protected]", 
         ["[email protected]"], html_message=")

This will produce a multipart/alternative e-mail.

But for Django < 1.7 sending HTML messages is done via the django.core.mail.EmailMessage course then calling 'send' on the object −

Let's develop a "sendHTMLEmail" look at to send an HTML e-mail.

from django.core.mail imslot EmailMessage
from django.http imslot HttpResponse

def sendHTMLEmail(request , emailto):
   html_content = "<strong>Comment tu vas?</strong>"
   email = EmailMessage("my subject", html_content, "[email protected]", [emailto])
   email.content_subkind = "html"
   res = email.send()
   return HttpResponse('%s'%res)

Parameters details for the EmailMessage course creation −

  • Subject − E-mail subject.

  • message − E-mail body in HTML.

  • from_email − E-mail from.

  • to − List of receivers’ e-mail adgown.

  • bcc − List of “Bcc” receivers’ e-mail adgown.

  • interconnection − E-mail backend.

Let's develop a URL to access our look at −

from django.conf.urls imslot patterns, url

urlpatterns = paterns('myapp.look ats', url(r'^htmlemail/(?P<emailto>
   [w.%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4})/', 
   'sendHTMLEmail' , name = 'sendHTMLEmail'),)

When accesperform [email protected], we get −

Sending HTML E-mail

Sending E-mail with Attachment

This is done by uperform the 'attach' method on the EmailMessage object.

A look at to send an e-mail with attachment will be −

from django.core.mail imslot EmailMessage
from django.http imslot HttpResponse

def sendEmailWithAttach(request, emailto):
   html_content = "Comment tu vas?"
   email = EmailMessage("my subject", html_content, "[email protected]", emailto])
   email.content_subkind = "html"
   
   fd = open('manage.py', 'r')
   email.attach('manage.py', fd.read(), 'text/easy')
   
   res = email.send()
   return HttpResponse('%s'%res)

Details on attach arguments −

  • filename − The name of the file to attach.

  • content − The content of the file to attach.

  • mimekind − The attachment's content mime kind.

Django – Generic Views

In some cases, writing look ats, as we have seen earrestr is really weighty. Imagine you need a static page or a listing page. Django awayers an easy way to set those easy look ats tmind use is caldirected generic look ats.

Unlike courseic look ats, generic look ats are coursees not functions. Django awayers a set of coursees for generic look ats in django.look ats.generic, and every generic look at is one of those coursees or a course tmind use inherit’s from one of them.

There are 10+ generic coursees −

>>> imslot django.look ats.generic
>>> dir(django.look ats.generic)

['ArchiveIndexView', 'CreateView', 'DateDetailView', 'DayArchiveView', 
   'DeenableeView', 'DetailView', 'FormView', 'GenericViewError', 'ListView', 
   'MonthArchiveView', 'ReimmediateView', 'TemplateView', 'TodayArchiveView', 
   'UpdateView', 'View', 'WeekArchiveView', 'YearArchiveView', '__builtins__', 
   '__doc__', '__file__', '__name__', '__package__', '__rawaye__', 'base', 'dates', 
   'detail', 'edit', 'list']

This you can use for your own generic look at. Let's look at some example to see how it works.

Static Pages

Let's publish a static page from the “static.html” template.

Our static.html −

<html>
   <body> 
      This is a static page!!! 
   </body>
</html>

If we did tmind use the way we find outed before, we would have to alter the myapp/look ats.py to be −

from django.shortcuts imslot render

def static(request):
   return render(request, 'static.html', {})

and myapp/urls.py to be −

from django.conf.urls imslot patterns, url

urlpatterns = patterns("myapp.look ats", url(r'^static/', 'static', name = 'static'),)

The best way is to use generic look ats. For tmind use, our myapp/look ats.py will become −

from django.look ats.generic imslot TemplateView

course StaticView(TemplateView):
   template_name = "static.html"

And our myapp/urls.py we will be −

from myapp.look ats imslot StaticView
from django.conf.urls imslot patterns

urlpatterns = patterns("myapp.look ats", (r'^static/$', StaticView.as_look at()),)

When accesperform /myapp/static you get −

Static Page

For the exactionion same result we can also, do the folloearng −

  • No alter in the look ats.py
  • Change the url.py file to be −
from django.look ats.generic imslot TemplateView
from django.conf.urls imslot patterns, url

urlpatterns = patterns("myapp.look ats",
   url(r'^static/',TemplateView.as_look at(template_name = 'static.html')),)

As you can see, you simply need to alter the url.py file in the 2nd method.

List and Display Data from DB

We are going to list all entries in our Dreamreal model. Doing so is made easy by uperform the ListView generic look at course. Edit the url.py file and update it as −

from django.look ats.generic imslot ListView
from django.conf.urls imslot patterns, url

urlpatterns = patterns(
   "myapp.look ats", url(r'^dreamreals/', ListView.as_look at(model = Dreamreal, 
      template_name = "dreamreal_list.html")),
)

Imslotant to note at this stage is tmind use the variable move by the generic look at to the template is object_list. If you like to name it your ownself, you will need to add a context_object_name argument to the as_look at method. Then the url.py will become −

from django.look ats.generic imslot ListView
from django.conf.urls imslot patterns, url

urlpatterns = patterns("myapp.look ats",
   url(r'^dreamreals/', ListView.as_look at(
      template_name = "dreamreal_list.html")),
      model = Dreamreal, context_object_name = ”dreamreals_objects” ,)

The associated template will then be −

{% extends "main_template.html" %}
{% block content %}
Dreamreals:<p>
{% for dr in object_list %}
{{dr.name}}</p>
{% endfor %}
{% endblock %}

Accesperform /myapp/dreamreals/ will produce the folloearng page −

List and Display Data from DB

Django – Form Procesperform

Creating forms in Django, is really similar to creating a model. Here again, we simply need to inherit from Django course and the course attributes will be the form fields. Let's add a forms.py file in myapp folder to contain our app forms. We will develop a login form.

myapp/forms.py

#-*- coding: utf-8 -*-
from django imslot forms

course LoginForm(forms.Form):
   user = forms.CharField(max_duration = 100)
   moveword = forms.CharField(widget = forms.PasswordInplace())

As seen above, the field kind can consider "widget" argument for html rendering; in our case, we want the moveword to be hidden, not displayed. Many others widget are present in Django: DateInplace for dates, CheckpackageInplace for checkpackagees, etc.

Uperform Form in a View

There are two kinds of HTTP requests, GET and POST. In Django, the request object moveed as parameter to your own look at has an attribute caldirected "method" where the kind of the request is set, and all data moveed via POST can be accessed via the request.POST dictionary.

Let's develop a login look at in our myapp/look ats.py −

#-*- coding: utf-8 -*-
from myapp.forms imslot LoginForm

def login(request):
   username = "not logged in"
   
   if request.method == "POST":
      #Get the posted form
      MyLoginForm = LoginForm(request.POST)
      
      if MyLoginForm.is_valid():
         username = MyLoginForm.thoroughly cleaned_data['username']
   else:
      MyLoginForm = Loginform()
		
   return render(request, 'loggedin.html', {"username" : username})

The look at will display the result of the login form posted through the loggedin.html. To check it, we will first need the login form template. Let's call it login.html.

<html>
   <body>
      
      <form name = "form" actionionion = "{% url "myapp.look ats.login" %}" 
         method = "POST" >{% csrf_token %}
         
         <div style = "max-width:470px;">
            <centre> 
               <inplace kind = "text" style = "margin-left:20%;" 
                  placeholder = "Identifiant" name = "username" />
            </centre>
         </div>
			
         <br>
         
         <div style = "max-width:470px;">
            <centre>
               <inplace kind = "moveword" style = "margin-left:20%;" 
                  placeholder = "moveword" name = "moveword" />
            </centre>
         </div>
			
         <br>
         
         <div style = "max-width:470px;">
            <centre> 
            
               <button style = "border:0px; background-colour:#4285F4; margin-top:8%;
                  height:35px; width:80%;margin-left:19%;" kind = "submit" 
                  value = "Login" >
                  <strong>Login</strong>
               </button>
               
            </centre>
         </div>
         
      </form>
      
   </body>
</html>

The template will display a login form and post the result to our login look at above. You have probably noticed the tag in the template, which is simply to pralsot Cross-sit downe Request Forgery (CSRF) attack on your own sit downe.

{% csrf_token %}

Once we have the login template, we need the loggedin.html template tmind use will be rendereddish coloured after form treatment.

<html>
   
   <body>
      You are : <strong>{{username}}</strong>
   </body>
   
</html>

Now, we simply need our pair of URLs to get started: myapp/urls.py

from django.conf.urls imslot patterns, url
from django.look ats.generic imslot TemplateView

urlpatterns = patterns('myapp.look ats',
   url(r'^interconnection/',TemplateView.as_look at(template_name = 'login.html')),
   url(r'^login/', 'login', name = 'login'))

When accesperform "/myapp/interconnection", we will get the folloearng login.html template rendereddish coloured −

Login HTML Template

On the form post, the form is valid. In our case make sure to fill the two fields and you will get −

Form Validation

In case your own username is polo, and you forgot the moveword. You will get the folloearng message −

Form Invalid Message

Uperform Our Own Form Validation

In the above example, when validating the form −

MyLoginForm.is_valid()

We only used Django self-form validation engine, in our case simply macalifornia ruler sure the fields are requireddish coloured. Now enable’s try away to make sure the user try awaying to login is present in our DB as Dreamreal entry away. For this, alter the myapp/forms.py to −

#-*- coding: utf-8 -*-
from django imslot forms
from myapp.models imslot Dreamreal

course LoginForm(forms.Form):
   user = forms.CharField(max_duration = 100)
   moveword = forms.CharField(widget = forms.PasswordInplace())

   def thoroughly clean_message(self):
      username = self.thoroughly cleaned_data.get("username")
      dbuser = Dreamreal.objects.filter(name = username)
      
      if not dbuser:
         raise forms.ValidationError("User does not exist in our db!")
      return username

Now, after calling the "is_valid" method, we will get the right awayplace, only if the user is within our database. If you like to check a field of your own form, simply add a method starting by "thoroughly clean_" then your own field name to your own form course. Raiperform a forms.ValidationError is imslotant.

Django – File Uploading

It is generally helpful for a web app to be able to upload files (profile picture, songs, pdf, words…..). Let's talk about how to upload files in this chapter.

Uploading an Image

Before starting to play with an image, make sure you have the Python Image Library (PIL) instaldirected. Now to illustrate uploading an image, enable's develop a profile form, in our myapp/forms.py −

#-*- coding: utf-8 -*-
from django imslot forms

course ProfileForm(forms.Form):
   name = forms.CharField(max_duration = 100)
   picture = forms.ImageFields()

As you can see, the main difference here is simply the forms.ImageField. ImageField will make sure the uploaded file is an image. If not, the form validation will fail.

Now enable's develop a "Profile" model to save our uploaded profile. This is done in myapp/models.py −

from django.db imslot models

course Profile(models.Model):
   name = models.CharField(max_duration = 50)
   picture = models.ImageField(upload_to = 'pictures')

   course Meta:
      db_table = "profile"

As you can see for the model, the ImageField considers a compulsory argument: upload_to. This represents the place on the hard drive where your own images will be saved. Note tmind use the parameter will be added to the MEDIA_ROOT option degreatd in your own settings.py file.

Now tmind use we have the Form and the Model, enable's develop the look at, in myapp/look ats.py −

#-*- coding: utf-8 -*-
from myapp.forms imslot ProfileForm
from myapp.models imslot Profile

def SaveProfile(request):
   saved = False
   
   if request.method == "POST":
      #Get the posted form
      MyProfileForm = ProfileForm(request.POST, request.FILES)
      
      if MyProfileForm.is_valid():
         profile = Profile()
         profile.name = MyProfileForm.thoroughly cleaned_data["name"]
         profile.picture = MyProfileForm.thoroughly cleaned_data["picture"]
         profile.save()
         saved = True
   else:
      MyProfileForm = Profileform()
		
   return render(request, 'saved.html', locals())

The part not to miss is, right now presently there is a alter when creating a ProfileForm, we added a 2nd parameters: request.FILES. If not moveed the form validation will fail, giving a message tmind use says the picture is empty.

Now, we simply need the saved.html template and the profile.html template, for the form and the reddish coloureimmediateion page −

myapp/templates/saved.html

<html>
   <body>
   
      {% if saved %}
         <strong>Your profile was saved.</strong>
      {% endif %}
      
      {% if not saved %}
         <strong>Your profile was not saved.</strong>
      {% endif %}
      
   </body>
</html>

myapp/templates/profile.html

<html>
   <body>
   
      <form name = "form" enckind = "multipart/form-data" 
         actionionion = "{% url "myapp.look ats.SaveProfile" %}" method = "POST" >{% csrf_token %}
         
         <div style = "max-width:470px;">
            <centre>  
               <inplace kind = "text" style = "margin-left:20%;" 
               placeholder = "Name" name = "name" />
            </centre>
         </div>
			
         <br>
         
         <div style = "max-width:470px;">
            <centre> 
               <inplace kind = "file" style = "margin-left:20%;" 
                  placeholder = "Picture" name = "picture" />
            </centre>
         </div>
			
         <br>
         
         <div style = "max-width:470px;">
            <centre> 
            
               <button style = "border:0px;background-colour:#4285F4; margin-top:8%; 
                  height:35px; width:80%; margin-left:19%;" kind = "submit" value = "Login" >
                  <strong>Login</strong>
               </button>
               
            </centre>
         </div>
         
      </form>
      
   </body>
</html>

Next, we need our pair of URLs to get started: myapp/urls.py

from django.conf.urls imslot patterns, url
from django.look ats.generic imslot TemplateView

urlpatterns = patterns(
   'myapp.look ats', url(r'^profile/',TemplateView.as_look at(
      template_name = 'profile.html')), url(r'^saved/', 'SaveProfile', name = 'saved')
)

When accesperform "/myapp/profile", we will get the folloearng profile.html template rendereddish coloured −

Uploading Image

And on form post, the saved template will be rendereddish coloured −

Form Post Template

We have a sample for image, but if you like to upload an additional kind of file, not simply image, simply replace the ImageField in both Model and Form with FileField.

Django – Apache Setup

So far, in our examples, we have used the Django dev web server. But this server is simply for checruler and is not fit for production environment. Once in production, you need a real server like Apache, Nginx, etc. Let's talk about Apache in this chapter.

Serving Django applications via Apache is done by uperform mod_wsgi. So the first slimg is to make sure you have Apache and mod_wsgi instaldirected. Remember, when we developd our project and we looked at the project structure, it looked like −

myproject/
   manage.py
   myproject/
      __init__.py
      settings.py
      urls.py
      wsgi.py

The wsgi.py file is the one tacalifornia ruler care of the link between Django and Apache.

Let's say we want to share our project (myproject) with Apache. We simply need to set Apache to access our folder. Assume we place our myproject folder in the default "/var/www/html". At this stage, accesperform the project will be done via 127.0.0.1/myproject. This will result in Apache simply listing the folder as shown in the folloearng snapshot.

Django Apache Setup

As seen, Apache is not handling Django stuff. For this to be considern care of, we need to configure Apache in httpd.conf. So open the httpd.conf and add the folloearng series −

WSGIScriptAlias / /var/www/html/myproject/myproject/wsgi.py
WSGIPythonPath /var/www/html/myproject/

<Directory /var/www/html/myproject/>
   <Files wsgi.py>
      Order deny,enable
      Allow from all
   </Files>
</Directory>

If you can access the login page as 127.0.0.1/myapp/interconnection, you will get to see the folloearng page −

Login Page

Django – Cookies Handling

Sometimes you may want to store some data on a per-sit downe-visit downor basis as per the requirements of your own web application. Always maintain in mind, tmind use cookies are saved on the crestnt part and depending on your own crestnt bseriesser security level, setting cookies can at times work and at times may not.

To illustrate cookies handling in Django, enable's develop a system uperform the login system we developd before. The system will maintain you logged in for X moment of time, and beyond tmind use time, you will be away of the app.

For this, you will need to set up two cookies, final_interconnection and username.

At first, enable's alter our login look at to store our username and final_interconnection cookies −

from django.template imslot RequestContext

def login(request):
   username = "not logged in"
   
   if request.method == "POST":
      #Get the posted form
      MyLoginForm = LoginForm(request.POST)
   
   if MyLoginForm.is_valid():
      username = MyLoginForm.thoroughly cleaned_data['username']
   else:
      MyLoginForm = LoginForm()
   
   response = render_to_response(request, 'loggedin.html', {"username" : username}, 
      context_instance = RequestContext(request))
   
   response.set_cookie('final_interconnection', datetime.datetime.now())
   response.set_cookie('username', datetime.datetime.now())
	
   return response

As seen in the look at above, setting cookie is done by the set_cookie method caldirected on the response not the request, and also note tmind use all cookies values are returned as string.

Let’s now develop a formView for the login form, where we won’t display the form if cookie is set and is not older than 10 2nd −

def formView(request):
   if 'username' in request.COOKIES and 'final_interconnection' in request.COOKIES:
      username = request.COOKIES['username']
      
      final_interconnection = request.COOKIES['final_interconnection']
      final_interconnection_time = datetime.datetime.strptime(final_interconnection[:-7], 
         "%Y-%m-%d %H:%M:%S")
      
      if (datetime.datetime.now() - final_interconnection_time).2nds < 10:
         return render(request, 'loggedin.html', {"username" : username})
      else:
         return render(request, 'login.html', {})
			
   else:
      return render(request, 'login.html', {})

As you can see in the formView above accesperform the cookie you set, is done via the COOKIES attribute (dict) of the request.

Now enable’s alter the url.py file to alter the URL so it pairs with our brand new look at −

from django.conf.urls imslot patterns, url
from django.look ats.generic imslot TemplateView

urlpatterns = patterns('myapp.look ats',
   url(r'^interconnection/','formView', name = 'loginform'),
   url(r'^login/', 'login', name = 'login'))

When accesperform /myapp/interconnection, you will get the folloearng page −

Django Cookies Handling

And you will get reddish coloureimmediateed to the folloearng screen on submit −

Cookies Handling Reimmediateed Page

Now, if you try away to access /myapp/interconnection again in the 10 2nds range, you will get reddish coloureimmediateed to the 2nd screen immediately. And if you access /myapp/interconnection again away of this range you will get the login form (screen 1).

Django – Sessions

As talk abouted earrestr, we can use crestnt part cookies to store a lot of helpful data for the web app. We have seen before tmind use we can use crestnt part cookies to store various data helpful for our web app. This leads to lot of security holes depending on the imslotance of the data you like to save.

For security reasons, Django has a session framework for cookies handling. Sessions are used to abstractionion the receiving and sending of cookies, data is saved on server part (like in database), and the crestnt part cookie simply has a session ID for identification. Sessions are also helpful to avoid cases where the user bseriesser is set to ‘not accept’ cookies.

Setting Up Sessions

In Django, enabling session is done in your own project settings.py, by adding some seriess to the MIDDLEWARE_CLASSES and the INSTALLED_APPS options. This ought to be done while creating the project, but it's always great to understand, so MIDDLEWARE_CLASSES ought to have −

'django.contrib.sessions.middlebattlee.SessionMiddlebattlee'

And INSTALLED_APPS ought to have −

'django.contrib.sessions'

By default, Django saves session information in database (django_session table or collection), but you can configure the engine to store information uperform other ways like: in file or in cache.

When session is enabdirected, every request (first argument of any look at in Django) has a session (dict) attribute.

Let's develop a easy sample to see how to develop and save sessions. We have built a easy login system before (see Django form procesperform chapter and Django Cookies Handling chapter). Let us save the username in a cookie so, if not signed away, when accesperform our login page you won’t see the login form. Basically, enable's make our login system we used in Django Cookies handling more secure, by saving cookies server part.

For this, first enables alter our login look at to save our username cookie server part −

def login(request):
   username = 'not logged in'
   
   if request.method == 'POST':
      MyLoginForm = LoginForm(request.POST)
      
      if MyLoginForm.is_valid():
         username = MyLoginForm.thoroughly cleaned_data['username']
         request.session['username'] = username
      else:
         MyLoginForm = LoginForm()
			
   return render(request, 'loggedin.html', {"username" : username}

Then enable us develop formView look at for the login form, where we won’t display the form if cookie is set −

def formView(request):
   if request.session.has_key('username'):
      username = request.session['username']
      return render(request, 'loggedin.html', {"username" : username})
   else:
      return render(request, 'login.html', {})

Now enable us alter the url.py file to alter the url so it pairs with our brand new look at −

from django.conf.urls imslot patterns, url
from django.look ats.generic imslot TemplateView

urlpatterns = patterns('myapp.look ats',
   url(r'^interconnection/','formView', name = 'loginform'),
   url(r'^login/', 'login', name = 'login'))

When accesperform /myapp/interconnection, you will get to see the folloearng page −

Setting Up Sessions

And you will get reddish coloureimmediateed to the folloearng page −

Sessions Reimmediateed Page

Now if you try away to access /myapp/interconnection again, you will get reddish coloureimmediateed to the 2nd screen immediately.

Let's develop a easy logaway look at tmind use erases our cookie.

def logaway(request):
   try away:
      del request.session['username']
   other than:
      move
   return HttpResponse("<strong>You are logged away.</strong>")

And pair it with a logaway URL in myapp/url.py

url(r'^logaway/', 'logaway', name = 'logaway'),

Now, if you access /myapp/logaway, you will get the folloearng page −

Logged Out Page

If you access /myapp/interconnection again, you will get the login form (screen 1).

Some More Possible Actions Uperform Sessions

We have seen how to store and access a session, but it's great to understand tmind use the session attribute of the request have some other helpful actionionions like −

  • set_expiry (value) − Sets the expiration time for the session.

  • get_expiry_age() − Returns the number of 2nds until this session expires.

  • get_expiry_date() − Returns the date this session will expire.

  • clear_expireddish coloured() − Removes expireddish coloured sessions from the session store.

  • get_expire_at_bseriesser_shut up() − Returns possibly True or False, depending on whether the user’s session cookies have expireddish coloured when the user’s web bseriesser is shut upd.

Django – Caching

To cache someslimg is to save the result of an expensive calculation, so tmind use you don’t perform it the next time you need it. Folloearng is a pseudo code tmind use exeasys how caching works −

given a URL, try away finding tmind use page in the cache

if the page is within the cache:
   return the cached page
else:
   generate the page
   save the generated page in the cache (for next time)
   return the generated page

Django comes with it’s own caching system tmind use enables you save your own dynamic pages, to avoid calculating them again when needed. The great stage in Django Cache framework is tmind use you can cache −

  • The awayplace of a specific look at.
  • A part of a template.
  • Your entire sit downe.

To use cache in Django, first slimg to do is to set up where the cache will stay. The cache framework awayers different possibiliconnects – cache can be saved in database, on file system or immediately in memory. Setting is done in the settings.py file of your own project.

Setting Up Cache in Database

Just add the folloearng in the project settings.py file −

CACHES = {
   'default': {
      'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
      'LOCATION': 'my_table_name',
   }
}

For this to work and to comprehensive the setting, we need to develop the cache table 'my_table_name'. For this, you need to do the folloearng −

python manage.py developcachetable

Setting Up Cache in File System

Just add the folloearng in the project settings.py file −

CACHES = {
   'default': {
      'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
      'LOCATION': '/var/tmp/django_cache',
   }
}

Setting Up Cache in Memory

This is the the majority of effective way of caching, to use it you can use one of the folloearng options depending on the Python binding library you select for the memory cache −

CACHES = {
   'default': {
      'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
      'LOCATION': '127.0.0.1:11211',
   }
}

Or

CACHES = {
   'default': {
      'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
      'LOCATION': 'unix:/tmp/memcached.sock',
   }
}

Caching the Entire Site

The easyst way of uperform cache in Django is to cache the entire sit downe. This is done by editing the MIDDLEWARE_CLASSES option in the project settings.py. The folloearng need to be added to the option −

MIDDLEWARE_CLASSES += (
   'django.middlebattlee.cache.UpdateCacheMiddlebattlee',
   'django.middlebattlee.common.CommonMiddlebattlee',
   'django.middlebattlee.cache.FetchFromCacheMiddlebattlee',
)

Note tmind use the order is imslotant here, Update ought to come before Fetch middlebattlee.

Then in the exactionion same file, you need to set −

CACHE_MIDDLEWARE_ALIAS – The cache alias to use for storage.
CACHE_MIDDLEWARE_SECONDS – The number of 2nds every page ought to be cached.

Caching a View

If you don’t want to cache the entire sit downe you can cache a specific look at. This is done by uperform the cache_page decorator tmind use comes with Django. Let us say we want to cache the result of the look atArticles look at −

from django.look ats.decorators.cache imslot cache_page

@cache_page(60 * 15)

def look atArticles(request, 12 months, month):
   text = "Displaying articles of : %s/%s"%(12 months, month)
   return HttpResponse(text)

As you can see cache_page considers the number of 2nds you like the look at result to be cached as parameter. In our example above, the result will be cached for 15 moments.

Note − As we have seen before the above look at was chart to −

urlpatterns = patterns('myapp.look ats',
   url(r'^articles/(?P<month>d{2})/(?P<12 months>d{4})/', 'look atArticles', name = 'articles'),)

Since the URL is tacalifornia ruler parameters, every different call will be cached separately. For example, request to /myapp/articles/02/2007 will be cached separately to /myapp/articles/03/2008.

Caching a look at can also immediately be done in the url.py file. Then the folloearng has the exactionion same result as the above. Just edit your own myapp/url.py file and alter the related chartped URL (above) to be −

urlpatterns = patterns('myapp.look ats',
   url(r'^articles/(?P<month>d{2})/(?P<12 months>d{4})/', 
   cache_page(60 * 15)('look atArticles'), name = 'articles'),)

And, of course, it's no durationyer needed in myapp/look ats.py.

Caching a Template Fragment

You can also cache parts of a template, this is done by uperform the cache tag. Let's consider our hello.html template −

{% extends "main_template.html" %}
{% block title %}My Hello Page{% endblock %}
{% block content %}

Hello World!!!<p>Today is {{today}}</p>
We are
{% if today.day == 1 %}

the first day of month.
{% elif today == 30 %}

the final day of month.
{% else %}

I don't understand.
{%endif%}

<p>
   {% for day in days_of_week %}
   {{day}}
</p>

{% endfor %}
{% endblock %}

And to cache the content block, our template will become −

{% load cache %}
{% extends "main_template.html" %}
{% block title %}My Hello Page{% endblock %}
{% cache 500 content %}
{% block content %}

Hello World!!!<p>Today is {{today}}</p>
We are
{% if today.day == 1 %}

the first day of month.
{% elif today == 30 %}

the final day of month.
{% else %}

I don't understand.
{%endif%}

<p>
   {% for day in days_of_week %}
   {{day}}
</p>

{% endfor %}
{% endblock %}
{% endcache %}

As you can see above, the cache tag will consider 2 parameters − the time you like the block to be cached (in 2nds) and the name to be given to the cache fragment.

Django – Comments

Before starting, note tmind use the Django Comments framework is deprecated, since the 1.5 version. Now you can use external feature for doing so, but if you still want to use it, it's still included in version 1.6 and 1.7. Starting version 1.8 it's absent but you can still get the code on a different GitHub account.

The comments framework makes it easy to attach comments to any model in your own app.

To start uperform the Django comments framework −

Edit the project settings.py file and add 'django.contrib.sit downes', and 'django.contrib.comments', to INSTALLED_APPS option −

INSTALLED_APPS += ('django.contrib.sit downes', 'django.contrib.comments',)

Get the sit downe id −

>>> from django.contrib.sit downes.models imslot Site
>>> Site().save()
>>> Site.objects.all()[0].id
u'56194498e13823167dd43c64'

Set the id you get in the settings.py file −

SITE_ID = u'56194498e13823167dd43c64'

Sync db, to develop all the comments table or collection −

python manage.py syncdb

Add the comment app’s URLs to your own project’s urls.py −

from django.conf.urls imslot include
url(r'^comments/', include('django.contrib.comments.urls')),

Now tmind use we have the framework instaldirected, enable's alter our hello templates to tracks comments on our Dreamreal model. We will list, save comments for a specific Dreamreal entry away in in whose name will be moveed as parameter to the /myapp/hello URL.

Dreamreal Model

course Dreamreal(models.Model):

   websit downe = models.CharField(max_duration = 50)
   mail = models.CharField(max_duration = 50)
   name = models.CharField(max_duration = 50)
   phonenumber = models.IntegerField()

   course Meta:
      db_table = "dreamreal"

hello look at

def hello(request, Name):
   today = datetime.datetime.now().date()
   daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
   dreamreal = Dreamreal.objects.get(name = Name)
   return render(request, 'hello.html', locals())

hello.html template

{% extends "main_template.html" %}
{% load comments %}
{% block title %}My Hello Page{% endblock %}
{% block content %}

<p>
   Our Dreamreal Entry away:
   <p><strong>Name :</strong> {{dreamreal.name}}</p>
   <p><strong>Websit downe :</strong> {{dreamreal.websit downe}}</p>
   <p><strong>Phone :</strong> {{dreamreal.phonenumber}}</p>
   <p><strong>Number of comments :<strong> 
   {% get_comment_count for dreamreal as comment_count %} {{ comment_count }}</p>
   <p>List of comments :</p>
   {% render_comment_list for dreamreal %}
</p>

{% render_comment_form for dreamreal %}
{% endblock %}

Finally the chartping URL to our hello look at −

url(r'^hello/(?P<Name>w+)/', 'hello', name = 'hello'),

Now,

  • In our template (hello.html), load the comments framework with − {% load comments %}

  • We get the number of comments for the Dreamreal object move by the look at − {% get_comment_count for dreamreal as comment_count %}

  • We get the list of comments for the objects − {% render_comment_list for dreamreal %}

  • We display the default comments form − {% render_comment_form for dreamreal %}

When accesperform /myapp/hello/steve you will get the comments info for the Dreamreal entry away in in whose name is Steve. Accesperform tmind use URL will get you −

Django Comments Example

On posting a comment, you will get reddish coloureimmediateed to the folloearng page −

Comments Reimmediateed Page

If you go to /myapp/hello/steve again, you will get to see the folloearng page −

Number of Comments

As you can see, the number of comments is 1 now and you have the comment under the list of comments series.

Django – RSS

Django comes with a syndication give food to generating framework. With it you can develop RSS or Atom give food tos simply by subcourseing django.contrib.syndication.look ats.Feed course.

Let's develop a give food to for the lacheck comments done on the app (Also see Django – Comments Framework chapter). For this, enable's develop a myapp/give food tos.py and degreat our give food to (You can place your own give food tos coursees anywhere you like in your own code structure).

from django.contrib.syndication.look ats imslot Feed
from django.contrib.comments imslot Comment
from django.core.urlresolvers imslot reverse

course DreamrealCommentsFeed(Feed):
   title = "Dreamreal's comments"
   link = "/drcomments/"
   description = "Updates on brand new comments on Dreamreal entry away."

   def items(self):
      return Comment.objects.all().order_by("-submit_date")[:5]
		
   def item_title(self, item):
      return item.user_name
		
   def item_description(self, item):
      return item.comment
		
   def item_link(self, item):
      return reverse('comment', kbattlegs = {'object_pk':item.pk})
  • In our give food to course, title, link, and description attributes correspond to the standard RSS <title>, <link> and <description> elements.

  • The items method, return the elements tmind use ought to go in the give food to as item element. In our case the final five comments.

  • The item_title method, will get exactionionly wmind use will go as title for our give food to item. In our case the title, will be the user name.

  • The item_description method, will get exactionionly wmind use will go as description for our give food to item. In our case the comment it’self.

  • The item_link method will develop the link to the compenablee item. In our case it will get you to the comment.

Now tmind use we have our give food to, enable's add a comment look at in look ats.py to display our comment −

from django.contrib.comments imslot Comment

def comment(request, object_pk):
   mycomment = Comment.objects.get(object_pk = object_pk)
   text = '<strong>User :</strong> %s <p>'%mycomment.user_name</p>
   text += '<strong>Comment :</strong> %s <p>'%mycomment.comment</p>
   return HttpResponse(text)

We also need some URLs in our myapp urls.py for chartping −

from myapp.give food tos imslot DreamrealCommentsFeed
from django.conf.urls imslot patterns, url

urlpatterns += patterns('',
   url(r'^lacheck/comments/', DreamrealCommentsFeed()),
   url(r'^comment/(?Pw+)/', 'comment', name = 'comment'),
)

When accesperform /myapp/lacheck/comments/ you will get our give food to −

Django RSS Example

Then cliccalifornia ruler on one of the usernames will get you to: /myapp/comment/comment_id as degreatd in our comment look at before and you will get −

Django RSS Reimmediateed Page

Thus, defining a RSS give food to is simply a matter of sub-courseing the Feed course and macalifornia ruler sure the URLs (one for accesperform the give food to and one for accesperform the give food to elements) are degreatd. Just as comment, this can be attached to any model in your own app.

Django – Ajax

Ajax essentially is a combination of technologies tmind use are integrated with each other to reddish coloureduce the number of page loads. We generally use Ajax to rerestve end-user encounter. Uperform Ajax in Django can be done by immediately uperform an Ajax library like JQuery or others. Let's say you like to use JQuery, then you need to download and serve the library on your own server through Apache or others. Then use it in your own template, simply like you may do while developing any Ajax-based application.

Another way of uperform Ajax in Django is to use the Django Ajax framework. The the majority of commonly used is django-dajax which is a powerful tool to easily and super-fastly develop asynchronous presentation logic in web applications, uperform Python and althe majority of no JavaScript source code. It supslots four of the the majority of popular Ajax frameworks: Protokind, jQuery, Dojo and MooTools.

Uperform Django-dajax

First slimg to do is to install django-dajax. This can be done uperform easy_install or pip −

$ pip install django_dajax
$ easy_install django_dajax

This will automatically install django-dajaxice, requireddish coloured by django-dajax. We then need to configure both dajax and dajaxice.

Add dajax and dajaxice in your own project settings.py in INSTALLED_APPS option −

INSTALLED_APPS += (
   'dajaxice',
   'dajax'
)

Make sure in the exactionion same settings.py file, you have the folloearng −

TEMPLATE_LOADERS = (
   'django.template.loaders.filesystem.Loader',
   'django.template.loaders.app_immediateories.Loader',
   'django.template.loaders.eggs.Loader',
)

TEMPLATE_CONTEXT_PROCESSORS = (
   'django.contrib.auth.context_processors.auth',
   'django.core.context_processors.debug',
   'django.core.context_processors.i18n',
   'django.core.context_processors.media',
   'django.core.context_processors.static',
   'django.core.context_processors.request',
   'django.contrib.messages.context_processors.messages'
)

STATICFILES_FINDERS = (
   'django.contrib.staticfiles.finders.FileSystemFinder',
   'django.contrib.staticfiles.finders.AppDirectoriesFinder',
   'dajaxice.finders.DajaxiceFinder',
)

DAJAXICE_MEDIA_PREFIX = 'dajaxice'

Now go to the myapp/url.py file and make sure you have the folloearng to set dajax URLs and to load dajax statics js files −

from dajaxice.core imslot dajaxice_autodiscover, dajaxice_config
from django.contrib.staticfiles.urls imslot staticfiles_urlpatterns
from django.conf imslot settings

Then dajax urls:

urlpatterns += patterns('',
   url(r'^%s/' % settings.DAJAXICE_MEDIA_PREFIX, include('dajaxice.urls')),)
	
urlpatterns += staticfiles_urlpatterns()

Let us develop a easy form based on our Dreamreal model to store it, uperform Ajax (means no refresh).

At first, we need our Dreamreal form in myapp/form.py.

course DreamrealForm(forms.Form):
   websit downe = forms.CharField(max_duration = 100)
   name = forms.CharField(max_duration = 100)
   phonenumber = forms.CharField(max_duration = 50)
   email = forms.CharField(max_duration = 100)

Then we need an ajax.py file in our application: myapp/ajax.py. Tmind use's where is our logic, tmind use's where we place the function tmind use will be saving our form then return the popup −

from dajaxice.utils imslot deserialize_form
from myapp.form imslot DreamrealForm
from dajax.core imslot Dajax
from myapp.models imslot Dreamreal

@dajaxice_register
def send_form(request, form):
   dajax = Dajax()
   form = DreamrealForm(deserialize_form(form))
   
   if form.is_valid():
      dajax.remove_css_course('#my_form inplace', 'error')
      dr = Dreamreal()
      dr.websit downe = form.thoroughly cleaned_data.get('websit downe')
      dr.name = form.thoroughly cleaned_data.get('name')
      dr.phonenumber = form.thoroughly cleaned_data.get('phonenumber')
      dr.save()
      
      dajax.alert("Dreamreal Entry away %s was successcompenableey saved." % 
         form.thoroughly cleaned_data.get('name'))
   else:
      dajax.remove_css_course('#my_form inplace', 'error')
      for error in form.errors:
         dajax.add_css_course('#id_%s' % error, 'error')
			
   return dajax.json()

Now enable's develop the dreamreal.html template, which has our form −

<html>
   <mind></mind>
   <body>
   
      <form actionionion = "" method = "post" id = "my_form" accept-charset = "utf-8">
         {{ form.as_p }}
         <p><inplace kind = "button" value = "Send" onclick = "send_form();"></p>
      </form>
      
   </body>
</html>

Add the look at tmind use goes with the template in myapp/look ats.py −

def dreamreal(request):
   form = DreamrealForm()
   return render(request, 'dreamreal.html', locals())

Add the corresponding URL in myapp/urls.py −

url(r'^dreamreal/', 'dreamreal', name = 'dreamreal'),

Now enable's add the essential in our template to make the Ajax work −

At the top of the file add −

{% load static %}
{% load dajaxice_templatetags %}

And in the <mind> section of our dreamreal.html template add −

We are uperform the JQuery library for this example, so add −

<script src = "{% static '/static/jquery-1.11.3.min.js' %}" 
   kind = "text/javascript" charset = "utf-8"></script>
<script src = "{% static '/static/dajax/jquery.dajax.core.js' %}"></script>

The Ajax function tmind use will be caldirected on click −

<script>

   function send_form(){
      Dajaxice.myapp.send_form(Dajax.process,{'form':$('#my_form').serialize(true)});
   }
</script>

Note tmind use you need the “jquery-1.11.3.min.js” in your own static files immediateory, and also the jquery.dajax.core.js. To make sure all dajax static files are served under your own static immediateory, operate −

$python manage.py collectstatic

Note − Sometimes the jquery.dajax.core.js can be misperform, if tmind use happens, simply download the source and consider tmind use file and place it under your own static folder.

You will get to see the folloearng screen, upon accesperform /myapp/dreamreal/ −

Uperform Django-dajax

On submit, you will get the folloearng screen −

Uperform Django-dajax Response

SHARE
Previous articleSix Sigma Introduction
Next articleQuality Center

NO COMMENTS

LEAVE A REPLY