Skip to content

Commit

Permalink
Merge pull request #10 from ridwaanhall:ridwaanhall/issue9
Browse files Browse the repository at this point in the history
Add 404 error handling and improve routing in blog
  • Loading branch information
ridwaanhall authored Jan 29, 2025
2 parents 70dfb1e + 6c3db57 commit b41bba7
Show file tree
Hide file tree
Showing 16 changed files with 237 additions and 105 deletions.
9 changes: 0 additions & 9 deletions LUMINA/asgi.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,3 @@
"""
ASGI config for LUMINA project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application
Expand Down
35 changes: 0 additions & 35 deletions LUMINA/settings.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,10 @@
"""
Django settings for LUMINA project.
Generated by 'django-admin startproject' using Django 4.2.18.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""

from pathlib import Path
from decouple import config

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config('DEV', default=False, cast=bool)

if not DEBUG:
Expand All @@ -35,8 +16,6 @@
ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
"whitenoise.runserver_nostatic",

Expand Down Expand Up @@ -85,9 +64,6 @@
WSGI_APPLICATION = 'LUMINA.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
Expand All @@ -96,9 +72,6 @@
}


# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
Expand All @@ -115,9 +88,6 @@
]


# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/

LANGUAGE_CODE = 'id-id'

TIME_ZONE = 'Asia/Jakarta'
Expand All @@ -127,14 +97,9 @@
USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/

STATIC_URL = 'static/'

STATIC_ROOT = BASE_DIR / 'staticfiles'

# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
18 changes: 2 additions & 16 deletions LUMINA/urls.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,11 @@
"""
URL configuration for LUMINA project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.urls import path, include
from . import views

urlpatterns = [
path('@ridwaanhall', views.PortfolioWebsiteView.as_view(), name='ridwaanhall'),
path('lanpage/', views.LandingPageView.as_view(), name='lanpage'),
path('<path:url>', views.CatchAllView.as_view(), name='catch_all'),

path('', include('absen.urls')),
path('blog/', include('blog.urls')),
]
46 changes: 44 additions & 2 deletions LUMINA/views.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,52 @@
from django.shortcuts import render
from django.views import View
from django.http import HttpResponseRedirect
from django.core.exceptions import SuspiciousOperation
from urllib.parse import urlparse

class PortfolioWebsiteView(View):
def get(self, request, *args, **kwargs):
return HttpResponseRedirect('https://ridwaanhall.vercel.app/')
try:
url = 'https://ridwaanhall.vercel.app/'
if not urlparse(url).scheme or not urlparse(url).netloc:
raise SuspiciousOperation("Invalid redirect URL")
return HttpResponseRedirect(url)
except SuspiciousOperation as e:
context = {
'error_code': 400,
'error_message': f'Bad Request: {e}'
}
return render(request, 'error.html', context, status=400)
except Exception as e:
context = {
'error_code': 500,
'error_message': f'Internal Server Error: {e}'
}
return render(request, 'error.html', context, status=500)

class LandingPageView(View):
def get(self, request, *args, **kwargs):
return HttpResponseRedirect('https://ngoding-me.vercel.app/')
try:
url = 'https://ngoding-me.vercel.app/'
if not urlparse(url).scheme or not urlparse(url).netloc:
raise SuspiciousOperation("Invalid redirect URL")
return HttpResponseRedirect(url)
except SuspiciousOperation as e:
context = {
'error_code': 400,
'error_message': f'Bad Request: {e}'
}
return render(request, 'error.html', context, status=400)
except Exception as e:
context = {
'error_code': 500,
'error_message': f'Internal Server Error: {e}'
}
return render(request, 'error.html', context, status=500)

class CatchAllView(View):
def get(self, request, *args, **kwargs):
context = {
'error_code': 404
}
return render(request, 'error.html', context, status=404)
9 changes: 0 additions & 9 deletions LUMINA/wsgi.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,3 @@
"""
WSGI config for LUMINA project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application
Expand Down
2 changes: 0 additions & 2 deletions absen/admin.py
Original file line number Diff line number Diff line change
@@ -1,3 +1 @@
from django.contrib import admin

# Register your models here.
2 changes: 0 additions & 2 deletions absen/models.py
Original file line number Diff line number Diff line change
@@ -1,3 +1 @@
from django.db import models

# Create your models here.
2 changes: 0 additions & 2 deletions absen/tests.py
Original file line number Diff line number Diff line change
@@ -1,3 +1 @@
from django.test import TestCase

# Create your tests here.
35 changes: 31 additions & 4 deletions absen/views.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,38 @@
from django.shortcuts import render
from django.views import View

# Create your views here.

class LuminaAppView(View):
def get(self, request):
return render(request, 'absen/absen.html')

try:
return render(request, 'absen/absen.html')
except (FileNotFoundError, ImportError) as e:
context = {
'error_code': 500,
'error_message': f'Module Error: {e}'
}
return render(request, 'error.html', context, status=500)
except Exception as e:
context = {
'error_code': 500,
'error_message': f'Unexpected Error: {e}'
}
return render(request, 'error.html', context, status=500)


class TermsView(View):
def get(self, request):
return render(request, 'absen/terms.html')
try:
return render(request, 'absen/terms.html')
except (FileNotFoundError, ImportError) as e:
context = {
'error_code': 500,
'error_message': f'Module Error: {e}'
}
return render(request, 'error.html', context, status=500)
except Exception as e:
context = {
'error_code': 500,
'error_message': f'Unexpected Error: {e}'
}
return render(request, 'error.html', context, status=500)
2 changes: 0 additions & 2 deletions blog/admin.py
Original file line number Diff line number Diff line change
@@ -1,3 +1 @@
from django.contrib import admin

# Register your models here.
2 changes: 1 addition & 1 deletion blog/blog_data.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from datetime import datetime
from django.utils import timezone


class BlogData:
blogs = [
Expand Down
2 changes: 0 additions & 2 deletions blog/models.py
Original file line number Diff line number Diff line change
@@ -1,3 +1 @@
from django.db import models

# Create your models here.
2 changes: 0 additions & 2 deletions blog/tests.py
Original file line number Diff line number Diff line change
@@ -1,3 +1 @@
from django.test import TestCase

# Create your tests here.
71 changes: 57 additions & 14 deletions blog/views.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,75 @@
from django.shortcuts import render
from django.views import View
from django.utils.text import slugify
from django.core.exceptions import SuspiciousOperation

from . import blog_data


class BlogListView(View):
def get(self, request):
blogs = blog_data.BlogData.blogs
try:
blogs = blog_data.BlogData.blogs
context = {
'blogs': blogs
}
return render(request, 'blog/blog.html', context)

context = {
'blogs': blogs
}
return render(request, 'blog/blog.html', context)
except AttributeError as e:
context = {
'error_code': 500,
'error_message': f'AttributeError: {e}'
}
return render(request, 'error.html', context, status=500)
except (TypeError, KeyError) as e:
context = {
'error_code': 500,
'error_message': f'Data Error: {e}'
}
return render(request, 'error.html', context, status=500)
except (FileNotFoundError, ImportError) as e:
context = {
'error_code': 500,
'error_message': f'Module Error: {e}'
}
return render(request, 'error.html', context, status=500)
except Exception as e:
context = {
'error_code': 500,
'error_message': f'Unexpected Error: {e}'
}
return render(request, 'error.html', context, status=500)

class BlogDetailView(View):
def get(self, request, title):

blogs = blog_data.BlogData.blogs

blog_post = next((item for item in blogs if slugify(item['title']) == title), None)
other_blogs = [item for item in blogs if slugify(item['title']) != title]
try:
if not isinstance(title, str):
raise SuspiciousOperation("Invalid title format")

blog_post = next((item for item in blogs if slugify(item['title']) == title), None)
other_blogs = [item for item in blogs if slugify(item['title']) != title]

if blog_post:
if blog_post:
context = {
'blog': blog_post,
'other_blogs': other_blogs
}
return render(request, 'blog/blog_detail.html', context)
else:
context = {
'error_code': 404
}
return render(request, 'error.html', context, status=404)

except SuspiciousOperation as e:
context = {
'error_code': 400
}
return render(request, 'error.html', context, status=400)
except Exception as e:
context = {
'blog' : blog_post,
'other_blogs': other_blogs
'error_code': 500
}
return render(request, 'blog/blog_detail.html', context)
else:
return render(request, 'blog/blog_not_found.html', status=404)
return render(request, 'error.html', context, status=500)
3 changes: 0 additions & 3 deletions manage.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'LUMINA.settings')
try:
from django.core.management import execute_from_command_line
Expand Down
Loading

0 comments on commit b41bba7

Please sign in to comment.