Skip to main content

Play with Django

What is Django?

Django is a Web framework like Rails, Spring, or ASP.NET MVC, but for Python. Using Django, you can quickly develop a Web application whose data (models) is stored in the database of your choosing, using templates for page views, and simple Python functions for controllers.
This blog outlines how to put together a complete, working (though minimal) Django website in 10 easy steps.
Note: the commands and code in this blog assume that Django is already installed on your computer. See Django’s home page, https://www.djangoproject.com/, for how to do this.

Django in 10 steps

  1. Generate a Django project
  2. Generate a Django app
  3. Add the app to the installed apps settings
  4. Write the models
  5. Migrate the database
  6. Use the admin interface to add some data
  7. Create a template for the page view
  8. Code a view function
  9. Map a URL to the view
  10. Run the development server and enjoy the app

Step 1: Generate a Django project

To get started, use the provided django-admin script to create a new Django project:
django-admin startproject blog_example
This creates a project folder named “blog_example” with database, Django, and application settings. One project might consist of several applications that work together to implement a web site. Note that there is a nested folder with the project name for the site settings. The only file in the project folder is manage.py, which is the project-specific admin tool. The layout of the project so far is this:
blog_example
blog_example/blog_example
blog_example/blog_example/__init__.py
blog_example/blog_example/settings.py
blog_example/blog_example/urls.py
blog_example/blog_example/wsgi.py
blog_example/manage.py
We’ll use the default database, SQLite; you could edit settings.py in the project folder to use PostgreSQL, MySQL, or Oracle.
The built-in authentication and admin modules need access to the database. We’ll set this up with
python manage.py migrate

Step 2: Generate a Django app

Now we’ll generate our application. This will be an app that displays US States and their major cities. To create an application, we’ll use manage.py again:
python manage.py startapp stateinfo
This creates a new folder (really a Python package) for the application, under the main project folder. Now our layout looks like this:
blog_example
blog_example/blog_example
blog_example/blog_example/__init__.py
blog_example/blog_example/__init__.pyc
blog_example/blog_example/settings.py
blog_example/blog_example/settings.pyc
blog_example/blog_example/urls.py
blog_example/blog_example/wsgi.py
blog_example/db.sqlite3
blog_example/manage.py
blog_example/stateinfo
blog_example/stateinfo/__init__.py
blog_example/stateinfo/admin.py
blog_example/stateinfo/migrations
blog_example/stateinfo/migrations/__init__.py
blog_example/stateinfo/models.py
blog_example/stateinfo/tests.py
blog_example/stateinfo/views.py

Step 3: Add the app to the installed apps settings

Because Django is a framework, we let it organize our code for us. The only manual configuration needed at this point is to add our application to the project configuration. In blog_example/settings.py, add the following line to the INSTALLED_APPS tuple:
'stateinfo',

Step 4: Write the models

Our data will be stored in models, which are Python classes that map to database tables, using Django’s built-in Object Relational Mapper, or ORM. The model is the key to Django’s power; it describes everything about your data, so Django can automatically manage the database.
Models go in models.py in the app folder. For this app, we’ll create two models, State and City. Each state is associated with multiple cities, so we will use a foreign key to implement a one-to-many relation:
from django.db import models

  class State(models.Model):
    name = models.CharField(max_length=100)
    def __unicode(self):
      return self.name
  class City(models.Model):
    name = models.CharField(max_length=100)
    is_capital = models.BooleanField(default=False)
    state = models.ForeignKey(State)
    def __unicode(self):
      return self.name
Django supports a wide variety of field types. Tables can have a one-to-one, one-to-many, or many-to-many relationship, among others.

Step 5: Migrate the database

Once the models have been created, it’s time to build the database. Django uses migrations to keep track of changes to the database schema. When the database is created, and whenever you make a change to the models, you will need to migrate the changes:
python manage.py makemigrations
python manage.py migrate

Step 6: Use the admin interface to add some data

One of the really useful features of Django is that it automatically creates an admin site for your data. To set this up, add your models to the admin.py configuration file in the app folder:
from stateinfo.models import State, City
  admin.site.register(State)
  admin.site.register(City)
To access the admin site we need a username and password:
python manage.py createsuperuser
Django provides a built-in web server for development. Start it up with:
python manage.py runserver
Open a browser and go to http://localhost:8000/admin. Now you can add some states and cities. Note that a state must be created before you can add a city to it. You can use the + button to add a new state from the City admin form.
Django Administration
You can update your models to provide plural forms for classes/tables and other human-friendly data.
Note: do not use the built-in server for production applications

Step 7: Create a template for the page view

Now that you have some data in the database, you can display the data in the application. While you can return raw HTML from a view function, it is better to use templates for views. Templates are HTML files that contain Django placeholders, which will get filled in with data from the models.
Placeholders come in two flavors: {% %} surrounds code instructions, such as for loops and if tests; {{ }} contains variables.
The default location for templates is a folder named templates under the app folder, which is not created by default. Create the folder, then edit a file in that folder named states.html with the following content:
<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8" />
  <title>{{ title }}</title>
</head>
<body>
<h1>{{ title }}</h1>
{% for state in states %}
{{ state.name }}
<ul>
  {% for city in state.city_set.all %}
  <li>{{ city.name }}
    {% if city.is_capital %}(capital){% endif %}
    </li>
    {% endfor %}
</ul>
{% endfor %}
</body>
</html>

Step 8: Code a view function

To provide data from models to the template, Django uses view functions. These are called “controllers” in other web frameworks. View functions expected a request object, and return web content. By default, views go in the file views.py, although this is not required. In this case, the returned content will be the filled-in template:
from django.shortcuts import render
from stateinfo.models import State

def states(request):
    vars = {
        'title': "My List of States",
        'states': State.objects.all(),
    }
    return render(request, 'states.html', vars)
The render function processes the template, using a dictionary of variables, and returns it to the caller (typically a web browser). In this example, the ‘title’ variable is just a string to display on the page, and the ‘states’ variable, is a list of all the State objects in the database.

Step 9: Map a URL to the view

Now that there is a template for the page, and a controller to fill it in, we need to tell our site where to find our app. This is done via URL mapping:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from stateinfo.views import states

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', states),
)
Each URL uses a regular expression to match an incoming request. The regex ‘^$’ matches a null string, so the states view will be called for the top level of the web site (http://localhost:8000/).

Step 10: Run the development server and enjoy your app

Now that the model, view, and template have been created, go to the main site (http://localhost:8000/) to see the data displayed. If the server is not running, start it up with
python manage.py runserver

Summary

To create a web application with Django, you define the models, views, and controllers, and let Django take care of the big picture. For real-life apps, Django provides form management, authentication, session management, error handling, and anything else needed for a scalable, enterprise-capable application.
django
Click HERE for a zip file with the entire project.

Popular posts from this blog

How to read or extract text data from passport using python utility.

Hi ,  Lets get start with some utility which can be really helpful in extracting the text data from passport documents which can be images, pdf.  So instead of jumping to code directly lets understand the MRZ, & how it works basically. MRZ Parser :                 A machine-readable passport (MRP) is a machine-readable travel document (MRTD) with the data on the identity page encoded in optical character recognition format Most travel passports worldwide are MRPs.  It can have 2 lines or 3 lines of machine-readable data. This method allows to process MRZ written in accordance with ICAO Document 9303 (endorsed by the International Organization for Standardization and the International Electrotechnical Commission as ISO/IEC 7501-1)). Some applications will need to be able to scan such data of someway, so one of the easiest methods is to recognize it from an image file. I 'll show you how to retrieve the MRZ infor...

How to generate class diagrams pictures in a Django/Open-edX project from console

A class diagram in the Unified Modeling Language ( UML ) is a type of static structure diagram that describes the structure of a system by showing the system’s classes, their attributes, operations (or methods), and the relationships among objects. https://github.com/django-extensions/django-extensions Step 1:   Install django extensions Command:  pip install django-extensions Step 2:  Add to installed apps INSTALLED_APPS = ( ... 'django_extensions' , ... ) Step 3:  Install diagrams generators You have to choose between two diagram generators: Graphviz or Dotplus before using the command or you will get: python manage.py graph_models -a -o myapp_models.png Note:  I prefer to use   pydotplus   as it easier to install than Graphviz and its dependencies so we use   pip install pydotplus . Command:  pip install pydotplus Step 4:  Generate diagrams Now we have everything installed...

How to Remove course from Open-edX

Go to vagrant  => 1. In the edx-platform directory:  - cd /edx/app/edxapp/edx-platform 2. Run the following Django management command:   - sudo -u www-data /edx/bin/python.edxapp /edx/bin/manage.edxapp lms dump_course_ids --settings aws    - sudo -u www-data /edx/bin/python.edxapp /edx/bin/manage.edxapp lms dump_course_ids --settings=devstack 3. Find the course ID which you'd like to delete in the resulting list of course IDs. 4. Copy the course ID into the following command and run it:  - sudo -u www-data /edx/bin/python.edxapp /edx/bin/manage.edxapp cms delete_course <COURSE_ID> --settings aws  -   sudo -u www-data /edx/bin/python.edxapp /edx/bin/manage.edxapp cms delete_course <COURSE_ID> --settings=devstack  - You'll be asked to verify the deletion . To verify the deletion, run the command from step 2 above and ensure that the course ID is not in the list. Help reference : ...