<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:foaf="http://xmlns.com/foaf/0.1/" xmlns:og="http://ogp.me/ns#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xmlns:schema="http://schema.org/" xmlns:sioc="http://rdfs.org/sioc/ns#" xmlns:sioct="http://rdfs.org/sioc/types#" xmlns:skos="http://www.w3.org/2004/02/skos/core#" xmlns:xsd="http://www.w3.org/2001/XMLSchema#" version="2.0" xml:base="https://www.linuxjournal.com/tag/django">
  <channel>
    <title>Django</title>
    <link>https://www.linuxjournal.com/tag/django</link>
    <description/>
    <language>en</language>
    
    <item>
  <title>Django Models</title>
  <link>https://www.linuxjournal.com/content/django-models</link>
  <description>  &lt;div data-history-node-id="1338869" class="layout layout--onecol"&gt;
    &lt;div class="layout__region layout__region--content"&gt;
      
            &lt;div class="field field--name-field-node-image field--type-image field--label-hidden field--item"&gt;  &lt;img src="https://www.linuxjournal.com/sites/default/files/nodeimage/story/django-logo-positive_1.png" width="640" height="223" alt="" typeof="foaf:Image" class="img-responsive" /&gt;&lt;/div&gt;
      
            &lt;div class="field field--name-node-author field--type-ds field--label-hidden field--item"&gt;by &lt;a title="View user profile." href="https://www.linuxjournal.com/users/reuven-lerner" lang="" about="https://www.linuxjournal.com/users/reuven-lerner" typeof="schema:Person" property="schema:name" datatype="" xml:lang=""&gt;Reuven Lerner&lt;/a&gt;&lt;/div&gt;
      
            &lt;div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"&gt;&lt;p&gt;
In my last article, I continued looking at the Django Web framework,
showing
how you can create and modify models. As you saw, Django expects you
to describe your models using Python code. The model description is
then transformed into SQL and compared with any previous version of
the model that might have existed. Django then creates a
"migration",
a file that describes how you can move from one version of the model
definition to the next. A migration is a fantastic tool, one that
allows developers to move their database forward (and backward) in
defined chunks. Migrations make it easier to collaborate with others
and upgrade existing applications.
&lt;/p&gt;
&lt;p&gt;
The thing is, migrations have little or nothing to do with the
day-to-day application that you want to run. They are useful for the
creation and maintenance of your application's models, but in your
application, you're going to want to use the models themselves.
&lt;/p&gt;

&lt;p&gt;
So in this article, I look at Django's ORM (object-relational
mapper). You'll see how how Django allows you to perform all the
traditional CRUD (create-read-update-delete) actions you need and
expect within your application, so that you can use a database to power
your Web application.
&lt;/p&gt;

&lt;p&gt;
For the purposes of this article, I'll be using the "atfapp"
application within the "atfapp" project that I created in last
month's article. The model, of an appointment calendar, is defined as follows in
atfapp/models.py:

&lt;/p&gt;&lt;pre&gt;&lt;code&gt;
class Appointment(models.Model):
    starts_at = models.DateTimeField()
    ends_at = models.DateTimeField()
    meeting_with = models.TextField()
    notes = models.TextField()
    minutes = models.TextField()
    def __str__(self):
        return "{} - {}: Meeting with {} 
           ↪({})".format(self.starts_at,
                                self.ends_at,
                                self.meeting_with,
                                self.notes)
&lt;/code&gt;&lt;/pre&gt;


&lt;p&gt;
As you can see, the above model has four fields, indicating when the
meeting starts, ends, with whom you are meeting and notes for before
the meeting starts. The first two fields are defined to be DateTime
fields in Django, which is translated into an SQL TIMESTAMP time in
the database.
&lt;/p&gt;


&lt;h3&gt;
Creating a New Appointment&lt;/h3&gt;

&lt;p&gt;
The easiest and best way to get your hands dirty with Django models is
to use the Django interactive shell—meaning, the Python interactive
shell within the Django environment. Within your project, just type:

&lt;/p&gt;&lt;pre&gt;&lt;code&gt;
django-admin shell
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;
and you'll be placed in the interactive Python interpreter—or if
you have it installed, in IPython. At this point, you can start to
interact with your project and its various applications. In order to
work with your Appointment object, you need to import it. Thus, the
first thing I do is write:

&lt;/p&gt;&lt;/div&gt;
      
            &lt;div class="field field--name-node-link field--type-ds field--label-hidden field--item"&gt;  &lt;a href="https://www.linuxjournal.com/content/django-models" hreflang="und"&gt;Go to Full Article&lt;/a&gt;
&lt;/div&gt;
      
    &lt;/div&gt;
  &lt;/div&gt;

</description>
  <pubDate>Tue, 27 Oct 2015 19:50:28 +0000</pubDate>
    <dc:creator>Reuven Lerner</dc:creator>
    <guid isPermaLink="false">1338869 at https://www.linuxjournal.com</guid>
    </item>
<item>
  <title>Django Models and Migrations</title>
  <link>https://www.linuxjournal.com/content/djangos-migrations-make-it-easy-define-and-update-your-database-schema</link>
  <description>  &lt;div data-history-node-id="1338787" class="layout layout--onecol"&gt;
    &lt;div class="layout__region layout__region--content"&gt;
      
            &lt;div class="field field--name-field-node-image field--type-image field--label-hidden field--item"&gt;  &lt;img src="https://www.linuxjournal.com/sites/default/files/nodeimage/story/django-logo-positive_0.png" width="640" height="223" alt="" typeof="foaf:Image" class="img-responsive" /&gt;&lt;/div&gt;
      
            &lt;div class="field field--name-node-author field--type-ds field--label-hidden field--item"&gt;by &lt;a title="View user profile." href="https://www.linuxjournal.com/users/reuven-lerner" lang="" about="https://www.linuxjournal.com/users/reuven-lerner" typeof="schema:Person" property="schema:name" datatype="" xml:lang=""&gt;Reuven Lerner&lt;/a&gt;&lt;/div&gt;
      
            &lt;div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"&gt;&lt;p&gt;
In my last two articles, I looked at the Django Web application
framework, written in Python. Django's documentation describes it as
an MTV framework, in which the acronym stands for model, template
and views.
&lt;/p&gt;
&lt;p&gt;
When a request comes in to a Django application, the application's URL
patterns determine which view method will be invoked. The view method
can then, as I mentioned in previous articles, directly return
content to the user or send the contents of a template. The template
typically contains not only HTML, but also directives, unique to
Django, which allow you to pass along variable values, execute loops
and display text conditionally.
&lt;/p&gt;

&lt;p&gt;
You can create lots of interesting Web applications with just views
and templates. However, most Web applications also use a database, and
in many cases, that means a relational database. Indeed, it's a rare
Web application that doesn't use a database of some sort.
&lt;/p&gt;

&lt;p&gt;
For many years, Web applications typically spoke directly with the
database, sending SQL via text strings. Thus, you would say something
like:

&lt;/p&gt;&lt;pre&gt;&lt;code&gt;
s = "SELECT first_name, last_name FROM Users where id = 1"
&lt;/code&gt;&lt;/pre&gt;


&lt;p&gt;
You then would send that SQL to the server via a database client
library and retrieve the results using that library. Although this
approach does allow you to harness the power of SQL directly, it means
that your application code now contains text strings with another
language. This mix of (for example) Python and SQL can become
difficult to maintain and work with. Besides, in Python, you're used to
working with objects, attributes and methods. Why can't you access
the database that way?
&lt;/p&gt;

&lt;p&gt;
The answer, of course, is that you can't, because relational databases
eventually do need to receive SQL in order to function
correctly. Thus, many programs use an ORM (object-relational
mapper), which translates method calls and object attributes into
SQL. There is a well established ORM in the Python world known as
SQLAlchemy. However, Django has opted to use its own ORM, with which
you define your database tables, as well as insert, update and retrieve
information in those tables.
&lt;/p&gt;

&lt;p&gt;
So in this article, I cover how you create models in Django, how you can
create and apply migrations based on those model definitions, and how
you can interact with your models from within a Django application.
&lt;/p&gt;


&lt;h3&gt;
Models&lt;/h3&gt;

&lt;p&gt;
A "model" in the Django world is a Python class that represents a
table in the database. If you are creating an appointment calendar,
your database likely will have at least two different tables:
People and Appointments. To represent these in Django, you create two
Python classes: Person and Appointment. Each of these models is defined
in the models.py file inside your application.
&lt;/p&gt;&lt;/div&gt;
      
            &lt;div class="field field--name-node-link field--type-ds field--label-hidden field--item"&gt;  &lt;a href="https://www.linuxjournal.com/content/djangos-migrations-make-it-easy-define-and-update-your-database-schema" hreflang="und"&gt;Go to Full Article&lt;/a&gt;
&lt;/div&gt;
      
    &lt;/div&gt;
  &lt;/div&gt;

</description>
  <pubDate>Thu, 30 Jul 2015 20:10:39 +0000</pubDate>
    <dc:creator>Reuven Lerner</dc:creator>
    <guid isPermaLink="false">1338787 at https://www.linuxjournal.com</guid>
    </item>
<item>
  <title>Django Templates</title>
  <link>https://www.linuxjournal.com/content/django-templates</link>
  <description>  &lt;div data-history-node-id="1338753" class="layout layout--onecol"&gt;
    &lt;div class="layout__region layout__region--content"&gt;
      
            &lt;div class="field field--name-field-node-image field--type-image field--label-hidden field--item"&gt;  &lt;img src="https://www.linuxjournal.com/sites/default/files/nodeimage/story/django-logo-positive.png" width="640" height="223" alt="" typeof="foaf:Image" class="img-responsive" /&gt;&lt;/div&gt;
      
            &lt;div class="field field--name-node-author field--type-ds field--label-hidden field--item"&gt;by &lt;a title="View user profile." href="https://www.linuxjournal.com/users/reuven-lerner" lang="" about="https://www.linuxjournal.com/users/reuven-lerner" typeof="schema:Person" property="schema:name" datatype="" xml:lang=""&gt;Reuven Lerner&lt;/a&gt;&lt;/div&gt;
      
            &lt;div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"&gt;&lt;p&gt;
In my last article (February 2015), I explained how to create a simple
Django project ("atfproject") and
inside that, create a simple application (atfapp). The
application worked in that if you went to the URL
http://localhost:8000/hello/Reuven,
you got the text "hello, Reuven".
&lt;/p&gt;

&lt;p&gt;
This was thanks to a combination of the view function:

&lt;/p&gt;&lt;pre&gt;&lt;code&gt;
def hello(request, name):
    return HttpResponse("hello, {}".format(name))
&lt;/code&gt;&lt;/pre&gt;


&lt;p&gt;
and the URL pattern that I created:

&lt;/p&gt;&lt;pre&gt;&lt;code&gt;
urlpatterns = patterns('',
           url(r'^hello/(?P&lt;name&gt;\w+)$', hello),
           url(r'^admin/', include(admin.site.urls)),
        )
&lt;/code&gt;&lt;/pre&gt;


&lt;p&gt;
Notice that in the first URL pattern, I define a named group,
"name", as a string of alphanumeric characters
(&lt;code&gt;\w+&lt;/code&gt;). The captured
characters then are passed to the view function's "name" parameter,
which allows the view function to accept and display the values within
the view function.
&lt;/p&gt;

&lt;p&gt;
Now, this does work, but if you're thinking that this is a pretty
awkward way to display text, as a string within a view function,
you're not alone. Indeed, aside from producing extremely small pieces
of text, you're likely never going to return HTML directly from a view
function. Instead, you'll use a template.
&lt;/p&gt;

&lt;p&gt;
This shouldn't come as a surprise to anyone who has been doing
Web development for any length of time. Every Web framework I have
used has some form of templates. Unfortunately, every Web framework
uses a unique type of template, with a new and different way to
integrate HTML and the sorts of dynamic content that you need to
present.
&lt;/p&gt;

&lt;p&gt;
So in this article, I describe how Django's templates work, allowing you to
generate dynamic content for your users.
&lt;/p&gt;


&lt;h3&gt;
Invoking Templates&lt;/h3&gt;

&lt;p&gt;
It's important to remember that Django's templates are HTML files with
a bit of extra code thrown in. And even saying that there is
"code"
in Django templates probably is exaggerating things a bit. The
template syntax is designed explicitly to reduce the amount of code
that you have to write, but also to reduce the amount of code that
is executed in the template. By removing code from the template and
putting it into your view methods (and models), you make your application
more modular, more flexible and more testable.
&lt;/p&gt;

&lt;p&gt;
To start with Django templates, you don't need to know anything
special. That's because a plain-old HTML file is a fine Django
template. Inside the "atfapp" application, let's create a new
subdirectory called templates. This is where Django will look for
your templates. You always can configure this differently by setting
the &lt;code&gt;TEMPLATE_DIRS&lt;/code&gt; variable inside the application's settings.
&lt;/p&gt;

&lt;p&gt;
Here is a simple template that I created and then put inside
atfapp/templates/hello.html:

&lt;/p&gt;&lt;/div&gt;
      
            &lt;div class="field field--name-node-link field--type-ds field--label-hidden field--item"&gt;  &lt;a href="https://www.linuxjournal.com/content/django-templates" hreflang="und"&gt;Go to Full Article&lt;/a&gt;
&lt;/div&gt;
      
    &lt;/div&gt;
  &lt;/div&gt;

</description>
  <pubDate>Wed, 24 Jun 2015 14:00:00 +0000</pubDate>
    <dc:creator>Reuven Lerner</dc:creator>
    <guid isPermaLink="false">1338753 at https://www.linuxjournal.com</guid>
    </item>

  </channel>
</rss>
