Getting Started
First we're gonna start a new project named
samplesite. If you have no idea how to create a new project you may refer to my tutorial
Python Getting Started with Django.
Creating our App
Next, we're gonna create and install a new app named
blog. If you have no idea on how to create and install a new app, you may visit my previous tutorial about
Python - Django Creating New App.
Creating our URLs
Go to your main app, which in my case named
samplesite folder and open
urls.py and change the content to:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('blog.urls')),
]
This will make our blog app as the index of our site.
Creating our Models
Next, we're gonna create our models which is the database of our app by opening our app directory, blog, then open
models.py and paste the ff codes:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=140)
body = models.TextField()
date = models.DateTimeField()
def __str__(self):
return self.title
In here, we have created table named
Post with columns
title, body and date. As you can see, we didn't create our id because django automatically does this for us.
Creating our Views
We're gonna create Generic View in this tutorial. Means that we are not going to use views.py to create our views.
Open
urls.py in our blog app directory and paste the ff codes:
from django.conf.urls import url, include
from django.views.generic import ListView, DetailView
from blog.models import Post
urlpatterns = [
url(r'^$', ListView.as_view(queryset=Post.objects.all().order_by("-date")[:25],template_name="blog/blog.html"))
]
Creating the Pages of our App
First, in our blog app, we create
templates directory. Then, inside templates, we create another directory named
blog. This is to avoid conflicts between our templates.
Then, create the following html files inside the blog.
header.html
<!DOCTYPE html>
{% load staticfiles %}
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}" type="text/css"> {% block content %}
{% endblock %}
blog.html
{% extends "blog/header.html" %}
{% block content %}
{% for post in object_list %}
<div class="panel panel-default"> <div class="panel-heading"> {{post.title}}
<i>{{ post.date|date:"F d, Y h:i A" }}
</i> {% endfor %}
{% endblock %}
Note: Dont forget to create our static folder that contains our bootstrap. This is for our static files. The bootstrap is included in the source code of this tutorial.
That's it for this tutorial. Please save this work for our next tutorial which will tackle about migration and admin. Happy Coding :)