যারা বাংলাদেশের ৩৬ তম Zend Certified Engineer এবং এই সাইট (w3programmers) এর স্বত্বাধিকারী এবং লেখক Masud Alam স্যার এর কাছে কাছে সপ্তাহে ২ দিন ক্লাস, ৬ দিন প্রাকটিস করতে চান তাদের জন্য আগামী ১ February 2018 (বৃহস্পতি এবং শুক্রবার সন্ধ্যা ৬:০০ টা রাত ৯:০০ টা) থেকে শুরু হতে যাচ্ছে ৫ মাস ব্যাপী Professional Web Design & Development With HTML, CSS, JAVASCRIPT, JQUERY, PHP & MySQL for Beginners কোর্স (এই কোর্স টি যারা ফ্রিল্যান্সিং এবং আউটসোর্সিং কাজে আগ্রহী বিশেষ ভাবে তাদের জন্য design করা হয়েছে। ), আগামী ৪ February 2018 ( রবি এবং মঙ্গলবার সন্ধ্যা ৬:০০ টা থেকে রাত ৯:০০ টা ) থেকে শুরু হতে যাচ্ছে ৪ মাস ব্যাপী Zend Certified PHP 7.1 Engineering কোর্স। যেটা Advance PHP কোর্স নামে পরিচিত । এবং ৫ February 2018 (সোম এবং বুধবার সন্ধ্যা ৬:০০ টা থেকে রাত ৯:০০ টা) থেকে শুরু হতে যাচ্ছে ৪ মাস ব্যাপী Laravel 5.5 Professional Beginning to Advance Course কোর্স ।এই কোর্স গুলোতে তিনি ছাত্রদের কে সপ্তাহে ২ দিন ৩ ঘন্টা করে ৬ ঘন্টা ক্লাস নিবেন , এবং শনি থেকে বৃহস্পতি সপ্তাহে ৬ দিন ই স্যার এর অফিসে বসে প্রাকটিস করার সুযোগ দিবেন ! এতে প্রাকটিস করা কালীন ছাত্র-ছাত্রীরা কোনো সমস্যায় পড়লে তাৎক্ষণিক স্যার এর সহযোগিতা পাবে . (উল্লেখ্য: Training গুলো স্যার তার techbeeo software company'r পাশাপাশি পরিচালনা করে থাকেন।) কোর্স গুলো সম্পর্কে বিস্তারিত জানতে পারবেন এই লিংকে : Course Details .কোর্স গুলোর প্রত্যেকটির ফী নির্ধারণ করা হয়েছে ৩০,০০০ টাকা। আগ্রহীদেরকে অতিসত্বর মাসুদ আলম স্যার এর সাথে যোগাযোগ করার জন্য অনুরোধ করা যাচ্ছে। স্যার এর মোবাইল নম্বর : ০১৭২২ ৮১ ৭৫ ৯১

Blog with Django

In this tutorial we will create a blog with Django. This blog will not be very fancy in design. Our main concern will be learning Django framework and its different features.

django

Django:
Let’s create a new folder called “django” anywhere you want. And go to that folder with your console. Run the following command. Don’t forget give the dot(.).

$ django-admin startproject mysite .

Let’s do some recap –

manage.py: is a script that helps with management of the site. With it we will be able to start a web server on our computer without installing anything else, amongst other things.

settings.py: file contains the configuration of your website.

urls.py: file contains a list of patterns used by urlresolver.

Now open settings.py with your IDE. Add the STATIC_ROOT just after the STATIC_URL.

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

The following lines contain the database configuration. We are using sqlite3 for our database. db.sqlite3 is our first database and the location will be our project directory.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

Now run the following migrate command to create our database –

$ python manage.py migrate

Django models
A model in Django is a special kind of object – it is saved in the database. A database is a collection of data. This is a place in which you will store information about users, your blog posts, etc. We are using a SQLite database to store our data. Django supports ORM. So, it doesn’t matter what database you are using. Just need to change the connection adapter of the database setting to use another DBMS like, MySQL, PostgreSQL etc.

For our blog posts we need some text content. So, we can design our blog model as –

Post
——–
title
text
author
created_date
published_date

The fields are self-explanatory. Title contains title, text is the text, author is the writer and the created as well as published dates.

Now run the following command from the console –

$ python manage.py startapp blog

The directory structure will be as –

1 django_setup

After creating an application we also need to tell Django that it should use it. So, open mysite/settings.py. We need to find INSTALLED_APPS and add a line containing ‘blog’.

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
)

In the blog/models.py file we define all objects called Models. Let’s open blog/models.py, remove everything from it and write code like this:

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

# Create your models here.
class Post(models.Model):
    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    text = 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

models.CharField – this is how you define text with a limited number of characters.
models.TextField – this is for long text without a limit. Sounds ideal for blog post content, right?
models.DateTimeField – this is a date and time.
models.ForeignKey – this is a link to another model.

Now run the following commands to prepare our database for our blog posts.

$ python manage.py makemigrations blog
$ python manage.py migrate blog

2 blog_migration

Django admin:
Let’s open the blog/admin.py file and replace its content with this:

from django.contrib import admin
from .models import Post

# Register your models here.
admin.site.register(Post)

This file is responsible for registering our model. If we have more then one model, we need to register all of them.

Now create a super user for our site. Provide the necessary infos –

$ python manage.py createsuperuser

Now run the server through –

$ python manage.py runserver

Open your browser and go to – http://127.0.0.1:8000/admin/

Give the user name and password and enter into the Django Admin dashboard.

3 django_first_post

Django URL
Django urls work with regular expression. From the URL, it evaluates the location string. You have to have minimum idea about regix to get through it. For our blog we will define urls inside django/blog/urls.py. To do so, we need to include this file path into our django/mysite/urls.py

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

Now create a file in django/blog/urls.py

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

urlpatterns = [
    url(r'^$', views.post_list, name='post_list'),
    url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'),
    url(r'^post/new/$', views.post_new, name='post_new'),
    url(r'^post/(?P<pk>[0-9]+)/edit/$', views.post_edit, name='post_edit'),
]

In this url patterns, we have created four pages for our blog site, post_list, post_detail, post_new and post_edit. In url pattern for post_detail and post_edit, “post/(?P[0-9]+)” is the primary key. So the url may be post/10 or post/10/edit.

For each post url, we have to create corresponding methods in views. So, let’s create edit our views.py as follows.

from django.utils import timezone
from .models import Post
from django.shortcuts import render, get_object_or_404, redirect
from .forms import PostForm


# Create your views here.
def post_list(request):

    posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    return render(request, 'blog/post_list.html', {'posts': posts})


def post_detail(request, pk):
    post = get_object_or_404(Post, pk=pk)
    return render(request, 'blog/post_detail.html', {'post': post})

def post_new(request):
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.published_date = timezone.now()
            post.save()
            return redirect('blog.views.post_detail', pk=post.pk)
    else:
        form = PostForm()
    return render(request, 'blog/post_edit.html', {'form': form})

def post_edit(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.published_date = timezone.now()
            post.save()
            return redirect('blog.views.post_detail', pk=post.pk)
    else:
        form = PostForm(instance=post)
    return render(request, 'blog/post_edit.html', {'form': form})

From line 1 to 4 we have imported our classes.

From line 8 to 11 we have defined our post_list page. Line 10 query ordered by published date. And line 11, return the rendered page for post_list with posts.

Line 14 to 16 defines post_detail. Line 15 is a little check of if the post exists or not.

Line 18 to 29 is the explanation of post_new. This method works for the new post submission. If the form is valid then, the post will be saved to our database with the post, author and publish date. Otherwise the post form will be re-appears, From line 19 to 29.

Line 31 to 43 defines post_edit method for our existing post. Here also we have checked, if the post exists or not and then go for saving our edited post, just like before.

Now we have to create a form class to handle our new and edited posts. So, create a new file forms.py in the same folder.

from django import forms

from .models import Post

class PostForm(forms.ModelForm):

    class Meta:
        model = Post
        fields = ('title', 'text',)

In this file we have created a PostForm class for our form posting. And we have defined title and text fields as editable.

Django Templating:
Now let’s go for our html templates to see our post view, new post submission and editing the post. So, create two folders “templates/blog” inside django/blog.

Django supports templating for viewing. So, first of all we need to create a base template for all of our pages. This base template contains all the basic html code with some additional Django templating language.

So, now create a file named base.html in blog/templates/ folder.

<body>
    <div>
        <h1><a href="/">Django Blog</a></h1>
        {% if user.is_authenticated %}
        <a href="{% url 'post_new' %}">Add</a>
        {% endif %}
    </div>
    <div>
        <div>
            <div>
            {% block content %}
            {% endblock %}
            </div>
        </div>
    </div>
</body>

From line 4 to 6, we have checked if the user is authenticated or not. Only authenticated users can add new post.

Line 11 and 12 is the block for the body content. The content of this section may vary depends on your need.

Now let’s create our first landing page post_list.html inside same folder and edit it as follows.

{% extends "blog/base.html" %}

{% block content %}
    {% for post in posts %}
        <div>

            <h1><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h1>
            <div>
                {{ post.published_date }}
            </div>
            <p>{{ post.text|linebreaks }}</p>
        </div>
    {% endfor %}
{% endblock content %}

In line 1 we have extended our base template.

Line 3 to 14 is the content of our body. Here, we just loop through our all post and display the content of the title, published date and body.

In line 7 we have created a link for the detail of the post. Line 11 displays the portion of content of the post. When the reader clicks on the post title, he will see the detail of the post in post detail page.

For our post detail, we need to create post_detail.html in the same folder.

{% extends "blog/base.html" %}

{% block content %}
    <div class="post">

        <a href="{% url 'post_edit' pk=post.pk %}">Edit</a>
        <h1>{{ post.title }}</h1>
        {% if post.published_date %}
            <div>
                {{ post.published_date }}
            </div>
        {% endif %}
        <p>{{ post.text|linebreaks }}</p>
    </div>
{% endblock %}

Just like before, line 1 extends the base template. And rest of the code is for content of our page.

In line 6, we have added one link for edit of the post.

Now let’s create our edit page named as post_edit.html in the same folder.

{% extends "blog/base.html" %}

{% block content %}
    <h1>New post</h1>
    <form method="POST">{% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Save</button>
    </form>
{% endblock %}

All the codes are almost same as before. There is a usual form submission fields. Here we have done a little security check, by giving csrf_token inside our form. It is a Django built in feature for it’s safety.

We are all done. Now open console and write the following command to run the server.

python manage.py runserver

Open your browser and go to http://127.0.0.1:8000

A full-featured Django blog is ready to go.

Ohhh.. Almost forgot to mention. Our blog is not good looking, because we have not added any styling. So, for the beautification, we can add all of our CSS and JS files inside base.html file and you will be ready to use all the classes and ids, as usual.

You can download, the whole project code from my github account.

Happy coding… 🙂

Blog with Django

Hej, I’m from Bangladesh. Learning programming is one of the freaking decisions I have taken in my life. Because, it makes me and my life crazy. I have great weakness on open source technologies. Perhaps, that’s why I do not know any closed source language. I fall in love with programming, when I started my undergraduate in East West University. Till now, I can not live without it.

One comment on “Blog with Django

Leave a Reply

Your email address will not be published. Required fields are marked *