0% found this document useful (0 votes)
16 views6 pages

Overview of Django Web Development

This document provides an overview of Django, a web development framework designed for rapid application development. It covers key aspects such as designing models, creating a dynamic admin interface, and structuring URLs and views for a database-driven web application. The document emphasizes the ease of use and flexibility of Django, encouraging users to explore further through tutorials and community resources.

Uploaded by

renish_mehta
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views6 pages

Overview of Django Web Development

This document provides an overview of Django, a web development framework designed for rapid application development. It covers key aspects such as designing models, creating a dynamic admin interface, and structuring URLs and views for a database-driven web application. The document emphasizes the ease of use and flexibility of Django, encouraging users to explore further through tutorials and community resources.

Uploaded by

renish_mehta
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

==================

Django at a glance
==================
Because Django was developed in a fast-paced newsroom environment, it was
designed to make common Web-development tasks fast and easy. Here's an informal
overview of how to write a database-driven Web app with Django.
The goal of this document is to give you enough technical specifics to
understand how Django works, but this isn't intended to be a tutorial or
reference -- but we've got both! When you're ready to start a project, you can
:doc:`start with the tutorial </intro/tutorial01>` or :doc:`dive right into more
detailed documentation </topics/index>`.
Design your model
=================
Although you can use Django without a database, it comes with an
object-relational mapper in which you describe your database layout in Python
code.
The :doc:`data-model syntax </topics/db/models>` offers many rich ways of
representing your models -- so far, it's been solving two years' worth of
database-schema problems. Here's a quick example, which might be saved in
the file ``mysite/news/[Link]``::
class Reporter([Link]):
full_name = [Link](max_length=70)
def __unicode__(self):
return self.full_name
class Article([Link]):
pub_date = [Link]()
headline = [Link](max_length=200)
content = [Link]()
reporter = [Link](Reporter)
def __unicode__(self):
return [Link]
Install it
==========
Next, run the Django command-line utility to create the database tables
automatically:
.. code-block:: bash
[Link] syncdb
The :djadmin:`syncdb` command looks at all your available models and creates
tables in your database for whichever tables don't already exist.
Enjoy the free API
==================
With that, you've got a free, and rich, :doc:`Python API </topics/db/queries>` t
o
access your data. The API is created on the fly, no code generation necessary:

.. code-block:: python
# Import the models we created from our "news" app
>>> from [Link] import Reporter, Article
# No reporters are in the system yet.
>>> [Link]()
[]
# Create a new Reporter.
>>> r = Reporter(full_name='John Smith')
# Save the object into the database. You have to call save() explicitly.
>>> [Link]()
# Now it has an ID.
>>> [Link]
1
# Now the new reporter is in the database.
>>> [Link]()
[<Reporter: John Smith>]
# Fields are represented as attributes on the Python object.
>>> r.full_name
'John Smith'
# Django provides a rich database lookup API.
>>> [Link](id=1)
<Reporter: John Smith>
>>> [Link](full_name__startswith='John')
<Reporter: John Smith>
>>> [Link](full_name__contains='mith')
<Reporter: John Smith>
>>> [Link](id=2)
Traceback (most recent call last):
...
DoesNotExist: Reporter matching query does not exist. Lookup parameters were
{'id': 2}
# Create an article.
>>> from datetime import date
>>> a = Article(pub_date=[Link](), headline='Django is cool',
...
content='Yeah.', reporter=r)
>>> [Link]()
# Now the article is in the database.
>>> [Link]()
[<Article: Django is cool>]
# Article objects get API access to related Reporter objects.
>>> r = [Link]
>>> r.full_name
'John Smith'
# And vice versa: Reporter objects get API access to Article objects.
>>> r.article_set.all()
[<Article: Django is cool>]

# The API follows relationships as far as you need, performing efficient


# JOINs for you behind the scenes.
# This finds all articles by a reporter whose name starts with "John".
>>> [Link](reporter__full_name__startswith="John")
[<Article: Django is cool>]
# Change an object by altering its attributes and calling save().
>>> r.full_name = 'Billy Goat'
>>> [Link]()
# Delete an object with delete().
>>> [Link]()
A dynamic admin interface: it's not just scaffolding -- it's the whole house
============================================================================
Once your models are defined, Django can automatically create a professional,
production ready :doc:`administrative interface </ref/contrib/admin/index>` -- a
Web
site that lets authenticated users add, change and delete objects. It's as easy
as registering your model in the admin site::
# In [Link]...
from [Link] import models
class Article([Link]):
pub_date = [Link]()
headline = [Link](max_length=200)
content = [Link]()
reporter = [Link](Reporter)
# In [Link] in the same directory...
import models
from [Link] import admin
[Link]([Link])
The philosophy here is that your site is edited by a staff, or a client, or
maybe just you -- and you don't want to have to deal with creating backend
interfaces just to manage content.
One typical workflow in creating Django apps is to create models and get the
admin sites up and running as fast as possible, so your staff (or clients) can
start populating data. Then, develop the way data is presented to the public.
Design your URLs
================
A clean, elegant URL scheme is an important detail in a high-quality Web
application. Django encourages beautiful URL design and doesn't put any cruft
in URLs, like ``.php`` or ``.asp``.
To design URLs for an app, you create a Python module called a :doc:`URLconf
</topics/http/urls>`. A table of contents for your app, it contains a simple map
ping
between URL patterns and Python callback functions. URLconfs also serve to
decouple URLs from Python code.

Here's what a URLconf might look like for the ``Reporter``/``Article``


example above::
from [Link] import patterns
urlpatterns = patterns('',
(r'^articles/(\d{4})/$', '[Link].year_archive'),
(r'^articles/(\d{4})/(\d{2})/$', '[Link].month_archive'),
(r'^articles/(\d{4})/(\d{2})/(\d+)/$', '[Link].article_detail'),
)
The code above maps URLs, as simple regular expressions, to the location of
Python callback functions ("views"). The regular expressions use parenthesis to
"capture" values from the URLs. When a user requests a page, Django runs
through each pattern, in order, and stops at the first one that matches the
requested URL. (If none of them matches, Django calls a special-case 404 view.)
This is blazingly fast, because the regular expressions are compiled at load
time.
Once one of the regexes matches, Django imports and calls the given view, which
is a simple Python function. Each view gets passed a request object -which contains request metadata -- and the values captured in the regex.
For example, if a user requested the URL "/articles/2005/05/39323/", Django
would call the function ``[Link].article_detail(request,
'2005', '05', '39323')``.
Write your views
================
Each view is responsible for doing one of two things: Returning an
:class:`~[Link]` object containing the content for the
requested page, or raising an exception such as :class:`~[Link].Http404`.
The rest is up to you.
Generally, a view retrieves data according to the parameters, loads a template
and renders the template with the retrieved data. Here's an example view for
``year_archive`` from above::
def year_archive(request, year):
a_list = [Link](pub_date__year=year)
return render_to_response('news/year_archive.html', {'year': year, 'arti
cle_list': a_list})
This example uses Django's :doc:`template system </topics/templates>`, which has
several powerful features but strives to stay simple enough for non-programmers
to use.
Design your templates
=====================
The code above loads the ``news/year_archive.html`` template.
Django has a template search path, which allows you to minimize redundancy among
templates. In your Django settings, you specify a list of directories to check
for templates. If a template doesn't exist in the first directory, it checks the
second, and so on.
Let's say the ``news/year_archive.html`` template was found. Here's what that

might look like:


.. code-block:: html+django
{% extends "[Link]" %}
{% block title %}Articles for {{ year }}{% endblock %}
{% block content %}
<h1>Articles for {{ year }}</h1>
{% for article in article_list %}
<p>{{ [Link] }}</p>
<p>By {{ [Link].full_name }}</p>
<p>Published {{ article.pub_date|date:"F j, Y" }}</p>
{% endfor %}
{% endblock %}
Variables are surrounded by double-curly braces. ``{{ [Link] }}``
means "Output the value of the article's headline attribute." But dots aren't
used only for attribute lookup: They also can do dictionary-key lookup, index
lookup and function calls.
Note ``{{ article.pub_date|date:"F j, Y" }}`` uses a Unix-style "pipe" (the "|"
character). This is called a template filter, and it's a way to filter the value
of a variable. In this case, the date filter formats a Python datetime object in
the given format (as found in PHP's date function).
You can chain together as many filters as you'd like. You can write custom
filters. You can write custom template tags, which run custom Python code behind
the scenes.
Finally, Django uses the concept of "template inheritance": That's what the
``{% extends "[Link]" %}`` does. It means "First load the template called
'base', which has defined a bunch of blocks, and fill the blocks with the
following blocks." In short, that lets you dramatically cut down on redundancy
in templates: each template has to define only what's unique to that template.
Here's what the "[Link]" template, including the use of :doc:`static files
</howto/static-files>`, might look like:
.. code-block:: html+django
{% load staticfiles %}
<html>
<head>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<img src="{% static "images/[Link]" %}" alt="Logo" />
{% block content %}{% endblock %}
</body>
</html>
Simplistically, it defines the look-and-feel of the site (with the site's logo),
and provides "holes" for child templates to fill. This makes a site redesign as
easy as changing a single file -- the base template.
It also lets you create multiple versions of a site, with different base
templates, while reusing child templates. Django's creators have used this

technique to create strikingly different cell-phone editions of sites -- simply


by creating a new base template.
Note that you don't have to use Django's template system if you prefer another
system. While Django's template system is particularly well-integrated with
Django's model layer, nothing forces you to use it. For that matter, you don't
have to use Django's database API, either. You can use another database
abstraction layer, you can read XML files, you can read files off disk, or
anything you want. Each piece of Django -- models, views, templates -- is
decoupled from the next.
This is just the surface
========================
This has been only a quick overview of Django's functionality. Some more useful
features:
* A :doc:`caching framework </topics/cache>` that integrates with memcached
or other backends.
* A :doc:`syndication framework </ref/contrib/syndication>` that makes
creating RSS and Atom feeds as easy as writing a small Python class.
* More sexy automatically-generated admin features -- this overview barely
scratched the surface.
The next obvious steps are for you to `download Django`_, read :doc:`the
tutorial </intro/tutorial01>` and join `the community`_. Thanks for your
interest!
.. _download Django: [Link]
.. _the community: [Link]

Common questions

Powered by AI

Django facilitates rapid development and an efficient workflow through several mechanisms. Firstly, it provides an automatic administrative interface as soon as models are defined, enabling authenticated users to manage content without extra coding. Secondly, Django's ORM and query API streamline database interactions, allowing developers to work with databases through Python code rather than SQL. Additionally, Django's URLconf and templating systems organize code and presentation, respectively, allowing developers to focus on unique application features rather than infrastructure .

Django's caching framework offers integration with various backends, including memcached, to store and retrieve data efficiently. This is important for web applications as it can significantly reduce database load by caching frequently accessed data, improving response times and scaling. Cached pages, fragments, or querysets reduce the need for repetitive database hits, leading to a more responsive application that handles increased traffic better. Efficient caching can improve user experience and reduce server costs, which is critical for large-scale and high-traffic environments .

One of the main advantages of Django's URL design is that it promotes clean and elegant URLs without the clutter of file extensions like '.php' or '.asp'. Additionally, URLconfs in Django decouple URLs from Python code. They use regular expressions to map URLs to Python callback functions, allowing developers to make changes in one place without affecting code elsewhere .

Django's architecture decouples its components—models, views, and templates—allowing developers to use or replace each independently. For instance, Django's template system is not mandatory even though it's well-integrated; developers can opt for other templating systems. Similarly, while Django provides a robust database API and ORM, developers can use different database abstraction layers or even other data sources like XML. This decoupling enhances flexibility, as changes in one component don't necessitate changes in another, allowing for greater customization and adaptability in web application development .

Django's template system contributes to reducing redundancy by using a feature called 'template inheritance.' This allows templates to extend a 'base' template, which defines the common structure or layout of web pages. Child templates can override specific blocks in the base template to define unique content for a page. This system requires developers to only define what's unique to each template, thus minimizing duplication .

Django's automated admin interface offers the advantage of creating a professional and production-ready backend without requiring developers to build it manually. It is integrated into the Django framework and activated simply by registering models with the admin site. This interface allows authenticated users to add, change, and delete objects. By creating the interface automatically, Django allows developers to focus on refining their application's functionality and appearance rather than backend management .

Django's template system allows site design variations, like mobile versions, through template inheritance and the use of different base templates. Developers can create multiple base templates for different site versions, such as desktop and mobile. Child templates can use these base templates by extending them, which allows the reuse of content-specific templates across different designs. By changing just the base template, a complete design overhaul or variation can be implemented site-wide, providing flexibility in maintaining multiple site versions .

Django handles changes to objects in the database using its ORM by providing standard operations such as save() and delete(). Changes to an object are made by modifying its attributes in Python code and then calling save() to update the database record. To remove an object, the delete() method is used. These operations allow developers to seamlessly interact with the database while working exclusively within Python, abstracting the underlying SQL .

In Django, database query results can be retrieved recursively across related models using the ORM's query capabilities. For example, if you have a Reporter and Article model with a ForeignKey relationship, you can retrieve all articles written by reporters in a specific way by filtering with related model fields. The ORM automatically performs efficient SQL JOIN operations under the hood to access related data, such as using 'Article.objects.filter(reporter__full_name__startswith="John")' to find all articles by a reporter whose name starts with 'John' .

Django's approach to URL pattern matching involves using regular expressions in URLconfs to map URLs to Python callback functions or views. This approach benefits web application developers by centralizing URL management and allowing flexible URL structures independent of file paths. The regular expressions are compiled at load time, offering fast matching. This design allows URLs to capture values into request parameters, enabling views to dynamically respond based on input. This facilitates clean and semantic URL designs, improving both site maintenance and user experience .

You might also like