บทความนี้สอนสร้างแอปย่อ URL ใน Django แปลง URL ยาวเป็นสั้น ใช้ไลบรารี Python ทั่วไป ไม่ใช่ Django-specific ใช้ได้ในโปรเจกต์ Python ใดๆ
ตัวอย่าง
สร้างโปรเจกต์และแอป ตั้งค่าพื้นฐาน รวม urls และเพิ่มแอปใน INSTALLED_APPS
ติดตั้ง pyshorteners:
pip install pyshorteners
ใน urls.py ของแอป:
from django.urls import path
from .views import url_shortner
urlpatterns = [
path('', url_shortner.as_view(), name="url-shortner"),
]
ใน views.py:
from django.shortcuts import render
import pyshorteners
from django.views import View
class url_shortner(View):
def post(self, request):
long_url = 'url' in request.POST and request.POST['url']
pys = pyshorteners.Shortener()
short_url = pys.tinyurl.short(long_url)
return render(request, 'urlShortner.html', context={'short_url': short_url, 'long_url': long_url})
def get(self, request):
return render(request, 'urlShortner.html')
สร้าง templates/urlShortner.html:
<!DOCTYPE html> <html>
<head> <title>Url Shortner</title> </head>
<body>
<div>
<h1>URL Shortner Application</h1>
<form method="POST">{% csrf_token %}
<input type="url" name="url" placeholder="Enter the link here" required>
<button>Shorten URL</button>
</form>
</div>
{% if short_url %}
<div>
<h3>Your shortened URL</h3>
<div>
<input type="url" id="short_url" value={{short_url}}>
<button name="short-url">Copy URL</button>
<small id="copied" class="px-5"></small>
</div>
<br>
<span><b>Long URL: </b></span> <a href="{{long_url}}">{{long_url}}</a>
</div>
{% endif %}
</body> </html>
เอาต์พุต
