Skip to content

Commit

Permalink
Admin (#5)
Browse files Browse the repository at this point in the history
* added url admin page

* added new fields

* updated admin ui
  • Loading branch information
angusgoody authored Nov 22, 2024
1 parent c1c0508 commit c089f33
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 0 deletions.
12 changes: 12 additions & 0 deletions shortener/admin.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
from django.contrib import admin

from shortener.models import URL


# Register your models here.
# Register the model with the admin site
@admin.register(URL)
class ShortenedURLAdmin(admin.ModelAdmin):
# Display the new fields in the admin list view
list_display = ('original_url', 'short_code', 'created_at', 'clicks', 'last_accessed')
search_fields = ('original_url', 'short_code')
list_filter = ('created_at', 'last_accessed')

readonly_fields = ('clicks', 'last_accessed')
23 changes: 23 additions & 0 deletions shortener/migrations/0002_url_clicks_url_last_accessed.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Generated by Django 5.1.3 on 2024-11-22 15:26

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('shortener', '0001_initial'),
]

operations = [
migrations.AddField(
model_name='url',
name='clicks',
field=models.PositiveIntegerField(default=0),
),
migrations.AddField(
model_name='url',
name='last_accessed',
field=models.DateTimeField(blank=True, null=True),
),
]
11 changes: 11 additions & 0 deletions shortener/models.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from django.db import models
from django.utils import timezone

# Create your models here.

Expand All @@ -7,5 +8,15 @@ class URL(models.Model):
short_code = models.CharField(max_length=10, unique=True)
created_at = models.DateTimeField(auto_now_add=True)

last_accessed = models.DateTimeField(null=True, blank=True)
clicks = models.PositiveIntegerField(default=0)

def __str__(self):
return f'{self.short_code} -> {self.original_url}'

# Method to update access info
def record_access(self):
self.last_accessed = timezone.now()
self.clicks += 1
self.save(update_fields=['last_accessed', 'clicks'])

5 changes: 5 additions & 0 deletions shortener/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,9 @@ def shortened_url(request, short_code):

def redirect_url(request, short_code):
url = get_object_or_404(URL, short_code=short_code)

# Update the access information
url.record_access()

# Redirect to the original URL
return redirect(url.original_url)

0 comments on commit c089f33

Please sign in to comment.