Django
[un(-)chained]

This is just an empty slide with speaker notes which y'all can't see

#python2.7

virtualenv env
source env/bin/activate
pip install -r requirements.txt

Linux machines

source env/bin/activate
cd /to/the/project/directory
django-admin.py startproject journalclub

Your directory structure will be something like this

Let's make some changes

change ALLOWED_HOSTS = [] to ALLOWED_HOSTS = ['*']

vim journalclub/settings.py

To create a database for our site, let's run the following in the console

python manage.py migrate

Now we can start the web server by running

python manage.py runserver 0:8001
http://127.0.0.1:8001/

Application

We will create a separate application inside our project

python manage.py startapp blogs
POST
title
description
author
created_date
published_date

Model


from django.db import models
from django.utils import timezone


class Post(models.Model):
    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    description = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title
vim journalclub/settings.py

# add blogs to the installed apps
  • The final step here is to add our new model to our database
  • First we have to make Django know that we have some changes in our model. (In this case we have just created it!) 
  • Go to the console and type the following
python manage.py makemigrations blogs
  • Django prepared a migration file for us that we now have to apply to our database
  •  Now type the following
python manage.py migrate blogs
  • Hurray! Our Post model is now in our database! 
  • How do i see it?
python manage.py dbshell

# in the sqlite shell
sqlite> .tables

# to see the column names of a table
sqlite> PRAGMA table_info(blogs_post);

# to quit
sqlite>.quit
sudo apt-get  install  sqlite3
  • Okay so far we have created a application and  it's model
  • Now that we have a DB to store our posts, how do we actually store values in the table?
  • Lets type the following in our console, which will launch an interactive shell
python manage.py shell
from blog.models import Post
Post.objects.all()
Post.objects.create(author='ambi', title='Sample title',\
        description='Test')

How do we query our table and populate values?

from django.contrib.auth.models import User
User.objects.all()
User.objects.create_user(username='test',\
        email='ambi@madstreetden.com',\
        password='test')
me = User.objects.get(username='ambi')
Post.objects.create(author=me,\
        title='Sample title',\
        description='Test')
  • We have created multiple posts
  • Now lets publish one
post = Post.objects.get(title="Sample title")
post.publish()
Post.objects.filter(published_date__lte=timezone.now())
Post.objects.filter(published_date__lte=timezone.now())
Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
Post.objects.filter(published_date__lte=timezone.now()).order_by('created_date')

Ordering and chaining query sets

Lets exit the interactive shell

URLs

Lets take a look at journalclub/urls.py

from django.conf.urls import include

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'', include('blogs.urls')),
]

Lets create a urls.py in the blogs app

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.post_list, name='post_list'),
]

Now lets run the server again

Views

Go into the blogs application and open views.py

from django.http import JsonResponse


def post_list(request):
    return JsonResponse({'status': 'okay', 'message': 'pong'},
            status=200)

But wait this is not what i want

from .models import Post

def post_list(request):
    data = Post.objects.all()
    fd = []
    for x in data:
        tmp = {}
        tmp['title'] = x.title
        tmp['author'] = x.author.username
        fd.append(tmp)
    return JsonResponse({'status': 'okay', 'message': fd},
            status=200)

Sending parameters in your HTTP request

from django.contrib.auth.models import User
import traceback, json

def post_create(request):
    try:
        payload=json.loads(request.body)
        username=payload['username']
        title=payload['title']
        description=payload['description']
        me = User.objects.get(username=username)
        p=Post.objects.create(author=me, title=title, description=description)
        return JsonResponse({'status': 'okay', 'message': '', 'data':{'post_id': p.id}},
                            status=200)
    except:
        err = traceback.format_exc()
        return JsonResponse({'status': 'okay', 'message': err},
                            status=500)

Adding the respective view to  urls.py

Publishing a new post

def publish_post(request):
    try:
        payload=json.loads(request.body)
        post_id = payload['post_id']
        p = Post.objects.get(id=post_id)
        p.publish()
        return JsonResponse({'status': 'okay', 'message': 'Post published',\
                            'data':{'title':p.title}},
                            status=200)
    except:
        err = traceback.format_exc()
        return JsonResponse({'status': 'okay', 'message': err},
                            status=500)

Thank you

Templates

def post_list(request):
    data = Post.objects.all()
    fd = []
    for x in data:
        tmp = {}
        tmp['title'] = x.title
        tmp['author'] = x.author.username
        fd.append(tmp)
    #return JsonResponse({'status': 'okay', 'message': '', 'data':fd},
    #        status=200)
    #return render(request, 'blogs/post_list.html', {})
    return render(request, 'blogs/posts_list.html', {'posts': data})

cd applications/templates/applicationname/template.html

Now, Thank you for real

I mean really

Lets get back to work

:)

Django unchained

By ambi

Django unchained

  • 638