Allow LAN admin access and add a campaign mint form (#11).
CI / test (pull_request) Successful in 6s
CI / test (pull_request) Successful in 6s
Serve /admin/ on 10.0.0.128 so it can be used from another machine on the network, and mint tracked short URLs from domain/campaign/source/metric.
This commit is contained in:
+54
-1
@@ -2,8 +2,15 @@ from django.contrib import admin, messages
|
||||
from django.forms import ModelForm, ValidationError as FormValidationError
|
||||
from django.utils.html import format_html
|
||||
|
||||
from links.forms import QuickMintForm, allowlisted_domain_choices
|
||||
from links.models import Click, ShortLink
|
||||
from links.services import ValidationError, generate_code, validate_target_url
|
||||
from links.services import (
|
||||
CodeCollisionError,
|
||||
ValidationError,
|
||||
create_link,
|
||||
generate_code,
|
||||
validate_target_url,
|
||||
)
|
||||
|
||||
admin.site.site_header = "URL shortener"
|
||||
admin.site.site_title = "Shortener admin"
|
||||
@@ -156,3 +163,49 @@ class ClickAdmin(admin.ModelAdmin):
|
||||
def user_agent_short(self, obj: Click) -> str:
|
||||
ua = obj.user_agent or ""
|
||||
return (ua[:48] + "…") if len(ua) > 48 else (ua or "—")
|
||||
|
||||
|
||||
def _quick_mint_context(request, extra_context=None):
|
||||
extra = extra_context.copy() if extra_context else {}
|
||||
extra.setdefault("quick_mint_form", QuickMintForm())
|
||||
extra.setdefault("created_link", None)
|
||||
extra.setdefault("allowed_domains", allowlisted_domain_choices())
|
||||
return extra
|
||||
|
||||
|
||||
def _mint_from_form(request, form: QuickMintForm):
|
||||
token_name = request.user.get_username() if request.user.is_authenticated else "admin"
|
||||
campaign = form.cleaned_data["campaign"].strip()
|
||||
return create_link(
|
||||
target_url=form.cleaned_data["target_url"],
|
||||
title=campaign,
|
||||
external_ref="",
|
||||
expires_at=None,
|
||||
token_name=token_name or "admin",
|
||||
)
|
||||
|
||||
|
||||
_orig_index = admin.site.index
|
||||
|
||||
|
||||
def _admin_index(request, extra_context=None):
|
||||
extra = _quick_mint_context(request, extra_context)
|
||||
form = QuickMintForm(request.POST or None)
|
||||
extra["quick_mint_form"] = form
|
||||
if request.method == "POST":
|
||||
if form.is_valid():
|
||||
try:
|
||||
link, minted = _mint_from_form(request, form)
|
||||
except CodeCollisionError:
|
||||
form.add_error(None, "Could not allocate a unique code.")
|
||||
else:
|
||||
extra["created_link"] = link
|
||||
extra["quick_mint_form"] = QuickMintForm()
|
||||
messages.success(
|
||||
request,
|
||||
"Short link created." if minted else "Existing active link returned.",
|
||||
)
|
||||
return _orig_index(request, extra)
|
||||
|
||||
|
||||
admin.site.index = _admin_index
|
||||
|
||||
Reference in New Issue
Block a user