Social Icons

Sunday, January 16, 2022

Django Practice Work: Creating a blog

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 file

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


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 makemigrations blog
python 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/ 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'


Here we used the
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:
  1. class PostList: In our example here we create a class to display the list of articles that we name
    which inherits from the class
    . 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
    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
    which inherits from the class
    . 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


Important! within the template you can access the list of posts thanks to the template variable called
which will be created automatically (ie the generic name

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/ file.
# mysite/
from django.contrib import admin
from django.urls import path
from blog import views

urlpatterns = [
    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
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 class="card-body">
                    <p class="card-text text-muted h6">{{ }} | {{ 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>
                <br />
            {% endfor %}

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.created_date }}</p>
        <p class="card-text ">{{ object.content | safe }}</p>

{% endblock content %}
Now if you type in your browser the url address : you will get: 


Younes Derfoufi

No comments:

Post a Comment

Learn Python For Beginners

Category Of Mobile Courses

Actualités (644) Adsense (1) Affiliation (1) Algebraic Topology (2) Algorithmic (1) all-news (30) Android (5) Android App (8) Android app without code (4) Android Apps (256) Android Development (4) Android download (2) Android OS (3) AngularJS (1) Automata theory and formal language (5) Bootstrap CSS (1) C programming (5) Category and Functor (8) CMS (3) Computer Glossary (18) Create Mobile App With Ionic Framework (2) CSS (2) CSS-Cascading-Style-Sheets (4) Developpement Java (13) Differential Geometry (1) Django-Python-Framework (15) dropshiping (26) Earn Money by Internet (4) Emplois (23) Framework php (2) Fraud (2) Github (2) HTML (9) IT News (3) Java For Beginners (10) Javascript (12) Kotlin Programming Language (8) Kotlin For Mobile Android (1) Linux Download (2) Marketing (5) Mobile (3) Mobile Courses (4) Mobile Marketing (4) MoneyGram (1) News (721) Node.js (5) Open Source (1) Photoshop (1) Protect Computer (1) Python (37) Python BeautifulSoup (1) Python For Data Science (2) Python PyQt (13) Python Reference (1) Python Source Code (10) Python-Books (6) Python-DVD-Training (1) Python-Exercises (305) Python-Framework (1) Python-IDE (1) Python-Kivy-Framework (2) Python-Modules (1) Python-pdf (2) Python-pyQt (1) python-temp (3) Référencement (2) Script PHP (2) Security (6) SEO (1) Snipping Tool: Faq (1) Social Networks (1) Source Code (4) Statistics With SPSS (2) Surveillance Software (1) Travail à domicile (6) Tutoriels php en vidéos (2) Tutoriels-MySql (6) tutoriels-php (19) Utilitaires (1) VPS (1) Web Hosting (1) Webcam (1) Webmarketing (11) Western Union (1) Windows 10 (1) Windows 7 (4) Windows 7 Faq (2) Windows 8 (1) Windows Accessories (1) Windows Download (8) Windows Drivers (1) Windows Fonts (1) Windows Power Shell (2) Windows Registry (2) Windows Security (18) Windows Software (2) Windows Spyware (2) Windows utilities (3) Windows Virus (2) Windows Vista (3) Windows Wireless (1) Windows xp (1) Wordpress (1)

Sample text

Sample Text

Blogger Templates