Blog Website using Django
Tags: blog, django, python
Published: 2020-12-04 05:19:31

Hello Everyone,
This is MADHUBAN KHATRI, a self-taught programmer. In this post, I am creating a **Blog Website using Pyton Framework - Django**. 
You need to create Django Project and an App. After this you have to install app in the settings.py INSTALLED APPS.

{% youtube z8S1xyq5HbQ%}


And follow these steps:-
#models.py
In this file, u have to create 4 models
* Contact
* Post
* Category
* Comment
```
from django.db import models
from django.contrib.auth.models import User

# Create your models here.

class Contact(models.Model):
    name = models.CharField(max_length=100, default='None')
    email = models.EmailField(max_length=100, default='abc@gmail.com')
    sub = models.CharField(max_length=100, default='None')
    msg = models.TextField(default='None')

    def __str__(self):
        return self.name


class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    post_img = models.ImageField(upload_to='pictures')
    category_name =  models.CharField(max_length=50, default="None")


    def __str__(self):
        return self.title


class Category(models.Model):
    post_name = models.ManyToManyField(Post)
    cat_name = models.CharField(max_length=50)

    def __str__(self):
        return self.cat_name

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    name = models.CharField(max_length=50)
    comment = models.TextField()

    def __str__(self):
        return self.comment
```
#admin.py
Register your models here.
```
from django.contrib import admin
from .models import Contact, Post, Category, Comment

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

```

#app1-urls.py
This is app1-urls.py and here you have to create URL for your website.

```
from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('post/<int:post_id>', views.post, name='post'),
    path('create_account/', views.create_account, name='create_account'),
    path('contact/', views.contact, name='contact'),
    path('contact/save', views.save_contact, name='save_contact'),
    path('create_post/', views.create_post, name='create_post'),
    path('save_post/', views.save_post, name='save_post'),
    path('search/',  views.search_query, name='search'),
    path('<str:post_title>/create_comment',  views.add_comment, name='add_comment'),


]
```

#views.py
In this file, u can create Logics for Blog website.

```
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from .models import Contact, Post, Category, Comment
from django.core.paginator import Paginator
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required

# Create your views here.
@login_required
def home(request):
    all_post = Post.objects.all().order_by('-id')
    paginator = Paginator(all_post,2, orphans=1)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    param = {'page_obj': page_obj, 'paginator': paginator, 'page_num': page_number}
    return render(request,"index.html", param)



def post(request, post_id):
    post_view = Post.objects.get(id=post_id)
    post_comments = post_view.comment_set.all().order_by('-id')
    rel_posts = Post.objects.filter(category_name=post_view.category_name).order_by('-id')
    post_cat =  Category.objects.filter(post_name=post_view)
    all_category = Category.objects.all()

    param = {'post_comments': post_comments, 'rel_post':rel_posts,'post_data':post_view, 'categorys': all_category,'post_cat':post_cat}
    return render(request,"post.html", param)


def signup(request):
    return render(request,"signup.html")

def create_account(request):
    if request.method == 'POST':
        firstName = request.POST['firstName']
        lastName = request.POST['lastName']
        mail = request.POST['mail']
        userName = request.POST['userName']
        pwd = request.POST['pwd']

        if firstName!="" or lastName!="" or mail!="" or userName!="" or pwd!="":
            create_user = User(username=userName,first_name=firstName,last_name=lastName,email=mail)
            create_user.set_password(pwd)
            create_user.save()
            return redirect('login')
        else:
            return HttpResponse("<script>alert('Please Fill the details carefully.')</script>")


def login(request):
    return render(request,"login.html")

def logged_in(request):
    if request.method == 'POST':
        uname = request.POST['uname']
        pwd = request.POST['pwd']
        # authenticate(username='john', password='secret')
        user = authenticate(username=uname, password=pwd)
        login(request,user)
        if user is not None:
            return redirect('home')
        else:
            return redirect('login')
    else:
        return HttpResponse("404 - Not found.")




def contact(request):
    return render(request,"contact.html")



def save_contact(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        mail = request.POST.get('email')
        subject = request.POST.get('subject')
        message = request.POST.get('message')

        save_contact = Contact(name = name, email = mail, sub = subject, msg = message)
        save_contact.save()
        return redirect('contact')


def create_post(request):
    some_categories = ['Django Tutorial', 'Python Tutorial', 'Tip and Tricks', 'SEO', 'Travel',
                       'Event', 'Fashion', 'Lifestyle', 'Sports' ,'Blogs', 'Photography', 'Others']
    return render(request, 'create_post.html', {'categories': some_categories})

def save_post(request):
    if request.method == 'POST':
        title = request.POST.get('title')
        content = request.POST.get('content')
        postImg = request.FILES['image']
        category = request.POST.get('category')

        save_post = Post(title = title, content = content, category_name = category, post_img = postImg)
        save_post.save()
        create_cat = Category(cat_name=category)
        if not Category.objects.filter(cat_name=category).exists():
            create_cat.save()
            create_cat.post_name.add(save_post)
        else:
            get_cat = Category.objects.get(cat_name=category)
            get_cat.post_name.add(save_post)
            return redirect("home")

    return redirect("home")



def search_query(request):
    if request.method == 'GET':
        search_term = request.GET.get('query')
        if search_term==None:
            return render(request, 'search_page.html')
        else:
            search_post_title = Post.objects.filter(title__icontains=search_term)
            search_post_content = Post.objects.filter(content__icontains=search_term)
            search_post_category = Post.objects.filter(category_name__icontains=search_term)
            search_post = search_post_title.union(search_post_content, search_post_category)

        param = {'search_post': search_post.order_by('-id')}

    return render(request, 'search_page.html', param)



#Create Comments
def add_comment(request, post_title):
    name = request.POST.get('name')
    comment = request.POST.get('comment')
    post = Post.objects.get(title=post_title)
    if name!="" and comment!="":
        create_comment = Comment(post=post, name=name, comment=comment)
        create_comment.save()
        return redirect(f'/post/{post.id}')



```