From 3229d7f2557ddbca50f9039114bddffc4f8da3f8 Mon Sep 17 00:00:00 2001 From: Andros Fenollosa Date: Sun, 21 Mar 2021 12:53:47 +0100 Subject: [PATCH] Add form Comments --- apps/back/consumers.py | 22 +++++++- apps/front/templates/layouts/main.html | 2 +- .../front/templates/partials/blog/single.html | 52 +++++++++++++++++-- apps/front/views.py | 4 +- my_demo/settings.py | 2 + 5 files changed, 75 insertions(+), 7 deletions(-) diff --git a/apps/back/consumers.py b/apps/back/consumers.py index cd3cb71..4f01830 100644 --- a/apps/back/consumers.py +++ b/apps/back/consumers.py @@ -27,8 +27,26 @@ class BlogConsumer(WebsocketConsumer): data['pag'] = pag if template == "partials/blog/single.html": + # Set data data["post"] = Post.objects.get(pk=data['id']) - data["comments"] = Comment.objects.filter(post__id=data['id']).all() + data["comments"] = Comment.objects.filter(post__id=data['id']).order_by("-created_on").all() + # Add new comment + data["newName"] = data['newName'] if 'newName' in data else '' + data["newMessage"] = data['newMessage'] if 'newMessage' in data else '' + newComment = 'newComment' in data + # Validation + error = (len(data["newName"]) == 0 or len(data["newMessage"]) == 0) and newComment + data["error"] = error + if newComment and not error: + # Insert + Comment( + name=data["newName"], + body=data["newMessage"], + post=Post.objects.get(pk=data['id']) + ).save() + # Clean form + data["newName"] = '' + data["newMessage"] = '' # Send message to WebSocket self.send( @@ -38,4 +56,4 @@ class BlogConsumer(WebsocketConsumer): "html": render_to_string(template, data) } ) - ) \ No newline at end of file + ) diff --git a/apps/front/templates/layouts/main.html b/apps/front/templates/layouts/main.html index f2578a0..661d281 100644 --- a/apps/front/templates/layouts/main.html +++ b/apps/front/templates/layouts/main.html @@ -30,7 +30,7 @@ diff --git a/apps/front/views.py b/apps/front/views.py index c19583a..358160b 100644 --- a/apps/front/views.py +++ b/apps/front/views.py @@ -1,3 +1,4 @@ +from django.conf import settings from django.shortcuts import render from apps.back.models import Post import uuid @@ -6,5 +7,6 @@ def all_articles(request): return render(request, 'layouts/main.html', { "CHANNEL": uuid.uuid4().hex[:20].upper(), "posts": Post.objects.all()[:3], - "pag": 1 + "pag": 1, + "DOMAIN": settings.DOMAIN }) diff --git a/my_demo/settings.py b/my_demo/settings.py index 8abcb9b..85562b2 100644 --- a/my_demo/settings.py +++ b/my_demo/settings.py @@ -15,6 +15,8 @@ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent +DOMAIN = os.environ.get("DOMAIN", "localhost") + # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/