Django – Part 2

Intro

Django’s slogan is “The web framework for perfectionists with deadlines.” It accomplishes this in a few different ways, forced compartmentalization, built in development tools, and every feature you could ask for. Below we will discuss how to get started, and how see how Django handles MVC.

Getting started:

You first want to setup a virtual env. I am using Anaconda, so I would type in:

  1. conda create –name <your env name> django
  2. source activate <your env name>

Then you would use Django’s great command line tools to create your first project:

  • django-admin startproject <your app name>

Once you the command above you will have your very first Django app. However it won’t do very much. You can execute the following command to run the application:

  • python manage.py runserver

As you can see its pretty boring and does not due much. Django is built around the idea of applications, being different modules in your over all application. These modules are separate from the main project and encapsulate the different features of your application. You create a Django app by then running:

  • python manage.py startapp <app name>

By running the command you get a new directory generated in your folder structure.

Getting started with MVC (MTV):

Dajango does not use the MVC design pattern per say, rather it uses the MTV design pattern. MTV stands for:

M – model : This is a simple python classes.

from django.db import models
class Topic(models.Model):
top_name = models.CharField(max_length=264,unique=True)
def __str__(self):
return self.top_name
class Webpage(models.Model):
topic = models.ForeignKey(Topic) # notice how easy it is to take care of foreign keys
name = models.CharField(max_length=264,unique=True)
url = models.URLField(unique=True)
def __str__(self):
return self.name

view raw
models_Django.py
hosted with ❤ by GitHub

As you can see it is very easy to start building the inter model relationships. All models need to inherit from the Model class. This is all possible due to Djangos built in ORM. The ORM abstracts away the whole concept of having to work with a SQL DB, since it also provides a easy method revise your tables to reflect changes to your python models. This is simply done by using the:

  • python manage.py migrate
  • python manage.py make migrations < Dajango app name>

T – template : This is your html that displays model data through server side rendering.

<!DOCTYPE html>
{% load staticfiles %}
<html>
<head>
<meta charset="utf-8">
<title>Django Level Two</title>
<link rel="stylesheet" href="{% static "css/mystyle.css" %}"/>
</head>
<body>
<h1>YOLO LIFE</h1>
<h1>Here are your acces records</h1>
<div class="djangotwo">
{% if access_records %}
<table>
<thead>
<th>Site Name</th>
<th>Date Accessed</th>
</thead>
{% for acc in access_records %}
<tr>
<td>
{{ acc.name }}
</td>
<td>
{{ acc.date }}
</td>
</tr>
{% endfor %}
</table>
{% else %}
<p>NO ACCESS RECORDS FOUND</p>
{% endif %}
</div>
<img src="{% static "images/b.jpg" %}" alt="Uh Oh, didn't show !">
</body>
</html>

view raw
template_Django.html
hosted with ❤ by GitHub

Note that to serve these files, they need to be outside your main Django app, and they need to be reregistered in the Django settings file.

V – view : This is interestingly your controller.

from django.shortcuts import render
from django.http import HttpResponse
from first_app.models import Topic,Webpage,AccessRecord
# Create your views here.
def index(request):
webpages_list = AccessRecord.objects.order_by('date')
date_dict = {'access_records': webpages_list}
my_dict = {'insert_me':"This is coming from da Index.html!!!"}
return render(request,'first_app/index.html',context=date_dict)

view raw
view_Django.py
hosted with ❤ by GitHub

As you can see above, you tie the data from your controller to your view by way of dictionaries. And tie your templates to your controllers to your views by specifying the url path name, and the file name.

A point of interest here, is that unlike some other frameworks your mapping a url to a method, rather then a whole class that contains different methods. This method mapping to is done using url.py files that exist both in the directory of the main project and the django app.

The main project directory:

from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
from first_app import views
urlpatterns = [
url(r'^$',views.index,name='index'),
url(r'^admin/', admin.site.urls),
url(r'^first_app/',include('first_app.urls')),
]

view raw
main_url.py
hosted with ❤ by GitHub

The Django app:

from django.conf.urls import url
from first_app import views
# is key word needs to be right
urlpatterns = [
url(r'^$',views.index, name='index'),
]

view raw
app_url.py
hosted with ❤ by GitHub

As you can see your using regex, to find a specific url, then mapping it to a method. The main urls.py file contains the main urls for the whole project and imports the urls specifically for the Django app. Whereas the Django app just contains the sub urls for that particular app.

The “http://127.0.0.1:8000/first_app&#8221; would hit the “first_app” app, then it would then hit any of the sub urls stored in the Django app urls file.

As you can see Django is not that hard use at all, and in most ways is significantly easier then other frameworks, that don’t have all these built in features. In the next blog post I will be discussing Models, the Django admin console, and how the ORM handles model changes.

You can find part one here.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s