Redirect to display of slug after shortening

This commit is contained in:
grisel-davy 2020-12-26 11:18:14 +01:00
parent 2bb50f2930
commit 6d9b9b9ac9
4 changed files with 28 additions and 11 deletions

View file

@ -124,3 +124,8 @@ USE_TZ = True
STATIC_URL = '/static/' STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static_files") STATIC_ROOT = os.path.join(BASE_DIR, "static_files")
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static/"),) STATICFILES_DIRS = (os.path.join(BASE_DIR, "static/"),)
# Parameters of the shortener:
RANDOM_SLUG_LEN = 5
UID_LEN = 10

View file

@ -0,0 +1,7 @@
{% extends 'base.html' %}
{% block content %}
Slug : {{slug.slug}}
Destination: {{slug.destination}}
Date: {{slug.date}}
{% endblock %}

View file

@ -16,11 +16,12 @@ Including another URLconf
from django.contrib import admin from django.contrib import admin
from django.urls import path from django.urls import path
from .views import index, AddSlug from .views import index, AddSlug, display
urlpatterns = [ urlpatterns = [
path('admin/', admin.site.urls), path('admin/', admin.site.urls),
#path('', index, name="index"), #path('', index, name="index"),
path('', AddSlug, name="index"), path('', AddSlug, name="index"),
#path(r"^display/(?P<slug_slug>[a-zA-Z0-9]+)$", display, name="display"),
path('display/<slug:slug>/', display, name='display'),
] ]

View file

@ -6,7 +6,7 @@
from django.shortcuts import render from django.shortcuts import render
from django.http import HttpResponseRedirect from django.http import HttpResponseRedirect
from .settings import TEMPLATES from .settings import TEMPLATES, RANDOM_SLUG_LEN, UID_LEN
from .models import Slug from .models import Slug
from .forms import SlugAddForm from .forms import SlugAddForm
@ -25,19 +25,23 @@ def AddSlug(request):
""" """
if request.method == 'POST': if request.method == 'POST':
form = SlugAddForm(request.POST) form = SlugAddForm(request.POST)
if form.is_valid(): if form.is_valid():
slug = form.save(commit=False) slug = form.save(commit=False)
if slug.slug == '': if slug.slug == '':
slug.slug = ''.join(random.choice(ensemble) for _ in range(5)) slug.slug = ''.join(random.choice(ensemble) for _ in range(RANDOM_SLUG_LEN))
slug.uid = ''.join(random.choice(ensemble) for _ in range(UID_LEN))
slug.uid = ''.join(random.choice(ensemble) for _ in range(20))
slug.save() slug.save()
return HttpResponseRedirect('display/{}'.format(slug.slug))
return HttpResponseRedirect('')
else: else:
form = SlugAddForm() form = SlugAddForm()
return render(request,'add_slug.html',{'form':form}) return render(request,'add_slug.html',{'form':form})
def display(request, slug):
slug = Slug.objects.filter(slug = slug).all()
if slug.count()!=1:
# TODO Redirect to 'unknown and display a message
return HttpResponsRedirect('display')
else:
context = {'slug':slug.get()}
return render(request,'display.html',context)