1 - Creating blog application: First step:

Before starting to create a blog with django, you must first complete the preliminary steps that we have already covered in previous tutorials:

  1. Create a django project named mysite
  2. Create an administrator interface 
  3. Create a django application and give it a name, for example: blog (configure its url)

After carrying out all these steps, you will have a blog project that looks like this: 

 


Then register your blog application at the settings.py file settings.py

INSTALLED_APPS = [
'blog.apps.BlogConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

2 - Creating and configuring the django blog model

from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin

STATUS = (
(0,"Draft"),
(1,"Publish")
)

class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts')
updated_date = models.DateTimeField(auto_now= True)
content = models.TextField()
created_date = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)

class Meta:
ordering = ['-created_date']

def __str__(self):
return self.title

Then apply the necessary migrations from the command line:

python manage.py makemigrations blog
python manage.py migrate

3 - Creating views

A Django view is just a Python function that receives a web request and returns a web response. We'll use class-based views, then map URLs for each view and create an HTML template for the data returned by the views. This time we will rely on the generic class-based view instead of the method-based view we have seen in previous tutorials. Let's edit our blog/views.py file:

from django.views import generic
from .models import Post

class PostList(generic.ListView):
queryset = Post.objects.filter(status=1).order_by('-created_date')
template_name = 'index.html'

class PostDetail(generic.DetailView):
model = Post
template_name = 'post_detail.html'

Remark

Here we used the

queryset

object, which is used by django to create a

list of objects

of a given model. We have already seen an example of a queryset allowing to return all the objects of the students model in the previous sections of this tutorial, not to mention queryset:

Students.objects.all()

.

  1. class PostList: In our example here we create a class to display the list of articles that we name
    PostList

    which inherits from the class

    generic.ListViews

    . We then create a

    queryset = Post.Object

    , to which we apply the filter

    (status = 1)

    method to display only published articles and omit those that are not. We then apply the

    order_by()

    method to generate a display ordered by date.

  2. class PostDetail: here we create a class to display the articles in detail, which we name
    PostDetail

    which inherits from the class

    generic.DetailView

    . The latter allows you to display the objects in detail provided you specify the model

    (model = Post)

    and specify the template file that will be used

    post_detail.html

    .

Remark

Important! within the template you can access the list of posts thanks to the template variable called

post_list

which will be created automatically (ie the generic name

'model_name_list'

).

4 - Configuring URL Patterns with Views

Now we need to configure the URLS with the views we just created above. When a user sends a request that requests a page on your blog application, the Django controller takes over to find the corresponding view via the mysite/urls.py file.

# mysite/urls.py
from django.contrib import admin
from django.urls import path
from blog import views

urlpatterns = [
path('admin/', admin.site.urls),
path('blog/' , views.PostList.as_view(), name='home'),
path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'),
]

5 - Building templates files

5.1 - Creating base template

Now to be able to continue your project you must create a

base.html

file which will be used by django as a base template. If you don't want to rack your brains, you can use ours

5.2 - Display of the articles list via the template templates/post_list.html

<!-- templates/post_list.html -->
{% extends "base.html" %}
{% block content %}

<div class="container">
<div class="row">
<!-- Blog Entries Column -->

{% for post in post_list %}
<div class="card">
<div class="card-header">

<h2 class="card-title">{{ post.title }}</h2>
</div>
<div class="card-body">
<p class="card-text text-muted h6">{{ post.author }} | {{ post.created_date}} </p>
<p class="card-text">{{post.content|slice:":200" }}</p>
<a href="{% url 'post_detail' post.slug %}" class="btn btn-danger">Read More →</a>
</div>
</div>
<br />
{% endfor %}

</div>
</div>
{%endblock%}

5.3 - Display of the article details via the template: templates/post_list.html

{% extends 'base.html' %}
{% block content %}

<div class="container">
<div class="row">
<div class="card-body">
<h1> {{ object.title }} </h1>
<p class=" text-muted">{{ post.author }} | {{ post.created_date }}</p>
<p class="card-text ">{{ object.content | safe }}</p>
</div>
</div>
</div>

{% endblock content %}

Now if you type in your browser the url address : http://127.0.0.1:8000/blog/ you will get: 

 

Younes Derfoufi
my-courses.net

Leave a Reply