Create My Website

Create My Website:

By ridhaos Oct, 2024

Creating personal websites does it hard? And Costing?

As we’ve all seen, especially after COVID-19, many IT companies have embraced remote work, opening up opportunities to hire developers from around the world. After I started exploring new opportunities and growing in my professional career, I went through many interviews. A common question from hiring managers was whether I had a repository where they could find my articles, code, or projects. The Problems I Faced:

  1. Organization: I was often unorganized and rarely pushed my work to GitHub or saved it to the cloud.
  2. Web Development Skills: As an embedded software developer, I was far removed from the world of web design and web development. However, I do have Python programming skills, so I thought, “Why not build my website using Python?” After some research, I discovered Django. Django stood out as a highly recommended web framework, and after reading the documentation and following the tutorial, I realized it’s surprisingly simple to create your own website with it.

Why This Guide?

If you’re like me with base knowledge in web-developing. If you want to quickly and efficiently create a website to showcase your work to hiring managers or share it on LinkedIn or also you want to create your own blog—you’re in the right place.

Let’s get started by setting up our environment.

Setting Up your environment :

For my side im using windows.

1. Install python:

Install Python using the Microsoft Store:

    C:\Users\ridhaos\> Python --version
    C:\Users\ridhaos\> pip --version

2. Install visual studio code.

Start Creating Your Website:

It’s Time to get our hands dirty, i hope your are motivated to start but before getting start we need to create our virtual environment, why we need to use virtual environment because : Virtual environments let you have a stable, reproducible, and portable environment. And as we will deploy our website it’s very easy to porting our website after.

How Start CMD.

C:\Users\ridhaos\myWebsite>python -m venv.
C:\Users\ridhaos\myWebsite>Scripts\activate.bat
(myWebsite) C:\Users\ridhaos\myWebsite>pip install django markdown pillow
  1. django : django framework to create our website.
  2. markdown : markdown framework help us to convert markdown to html.
  3. pillow : to add image to our website.

Create Django Project

Now, let's create our website project by running this command:

(myWebsite) C:\Users\ridhaos\myWebsite>django-admin startproject myPortfolio

Open myPortfolio directory with VS code by command line:

(myWebsite) C:\Users\ridhaos\myWebsite>cd myPortfolio & code .

myPortfolio.

After creating our project now let's now create application for my side i called blog:

(myWebsite) C:\Users\ridhaos\myWebsite>python manage.py startapp blog

After finishing = you will see blog directory created with python defined files. myPortfolio.

Let's start by Adding our blog application to our project:

  1. Open setting.py under myPortfolio\myPortfolio.
  2. Add blog to INSTALLED_APPS = [...]:
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
]
  1. Add at the end of setting.py configure media repository for images:
# Media files
import os
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
  1. Open urls.py under myPortfolio\myPortfolio, and update it like below:
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('', include('blog.urls')),
    path('admin/', admin.site.urls),
]

After updating urls.py and setting.py we already configured our project, now let's continue to configure our blog application.

  1. add urls.py file under myPortfolio\blog.
  2. add templates and static directories under myPortfolio\blog.
  3. under static add two directories js and css

Your repository now must be like the photo below: repository.

Start developping our blog app

All configuration and setting up project done, now the most important part of this tutorial. let's start by define our models (Data base model):

  1. Open models.py under myPortfolio\blog and create your model like this:
from django.db import models
from django.contrib.auth.models import User
from django.dispatch import receiver
from django.db.models.signals import pre_delete

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

# Create your models here.
class Post(models.Model):
    title       = models.CharField(max_length=256, unique=True, blank=False)
    slug        = models.SlugField(max_length=256, unique=True, blank=False)
    author      = models.ForeignKey(User, on_delete = models.CASCADE, related_name='blog_posts')
    created_at  = models.DateTimeField(auto_now_add=True)
    updated_at  = models.DateTimeField(auto_now=True)
    content     = models.TextField()
    tag_tech    = models.CharField(max_length=200, blank=True, null=True)
    status      = models.IntegerField(choices=STATUS, default=0)
    image       = models.ImageField(upload_to='post_images', null=False, blank=False)
    link_github = models.CharField(max_length=500, unique=True, blank=True, null=True)

    # Create Filter class for ordening shows
    class Meta():
        ordering = ['-created_at']

    # Create method return text field
    def __str__(self):
        return self.title

@receiver(pre_delete, sender=Post)
def delete_post_image(sender, instance, **Kwargs):
    instance.image.delete()

I create my class Post which contains (title, slug, author, created_at, updated_at, content, tag_tech, status, image, link_github) fields. and the last part of the code we define function called def delete_post_image(...): and this function used when we delete the from data base a Post the image delete also from directory.

Now we will create our templates, templates in django framework means html pages. We will start by adding 4 html files under myPortfolio\blog\templates:

from github project page copy the content of index, post_list, post_detail and base to your files.

Copy also css files, js file and /media/assets photo under the same repository as you these file to make our templates more beautifull.

"Please dont judge my webdesign its template that i download it from internet and update it, feel free to use any template you want or, you can use my template."

So, after configure it our templates now its time to go to the last step which is make all connected.

In this step need we will connect our templates to our views*, views in django mean connect getting data from database and send it back to templates. Open views.py** and add the following code:

from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Post
import markdown

# Create your views here.
class HomePage(ListView):
    template_name = 'index.html'
    model = Post

    def get_queryset(self):
        return Post.objects.filter(status=1).order_by('-created_at')

class PostList(ListView):
    template_name = 'post_list.html'
    model = Post

    def get_queryset(self):
        return Post.objects.filter(status=1).order_by('-created_at')

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

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        md = markdown.Markdown(extensions=["fenced_code", 'tables'])
        context['post'].content = md.convert(self.get_object().content)
        print(context['post'].content)
        return super().get_context_data(**kwargs)

Now, our views: HomePage, PostList, PostDetailView are configured. After the configuration of our views, the next step is to add urls and which url corresspond to one view, for this open urls.py and add the following code:

from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from . import views

urlpatterns = [
    path('', views.HomePage.as_view(), name="index"),
    path('blog/', views.PostList.as_view(), name="post_list"),
    path('blog/<slug:slug>/', views.PostDetailView.as_view(), name="post_detail"),
]

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Also need to update admin.py under myPortfolio\blog by the following code:

from django.contrib import admin
from .models import *

# Make admin page more readable
class PostAdmin(admin.ModelAdmin):
    list_display = ('title', 'slug', 'status', 'author', 'created_at')
    list_filter = ('created_at',)
    search_fields = ['title', 'content']

    def save_model(self, request, obj, form, change):
        obj.title = obj.title.title()
        return super().save_model(request, obj, form, change)

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

The moment has come to test our website, go back to CMD and start running the following commands:

  1. Fetch database:
(myWebsite) C:\Users\ridhaos\myWebsite>python manage.py migrate
  1. Create Post Model and save it in database:
(myWebsite) C:\Users\ridhaos\myWebsite>python manage.py makemigrations
  1. Fetch another time the data base:
(myWebsite) C:\Users\ridhaos\myWebsite>python manage.py migrate
  1. Create superuser with user and password:
(myWebsite) C:\Users\ridhaos\myWebsite>python manage.py createsuperuser
  1. Run server:
(myWebsite) C:\Users\ridhaos\myWebsite>python manage.py runserver

If all good and you don't have any error you must see the result, by going to localhost server http://127.0.0.1:8000/ and you can see your website is created: Website.

Congratulations!!! you website is ready...

Now the last part is to create a post, or article. got localhost admin page: http://127.0.0.1:8000/admin admin page.

Connect using your user and password. Go to post view and click on add post, fill the all field and for content field try to styling your lines with markdown format. and change the status to published, save and exit. Create post. Go back to your website, localhost http://127.0.0.1:8000/ and go to blog. You will see your blog is already published.

Conclusion:

This tutorial was just introduction to show how you can make a website in less than one hour, and give an ideao how python is powerfull in this domain especially in web domain. If you are interresting about all details you can follow django tutorial HERE where is so rich very simple to understand it and go deep in details. I hobe by the end of this articles make you curious about django, webapplication, or maybe python.