# Comments/views.py # (c) 2020 Derek Stevens from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .models import Comment, Thread from django.template import loader from django.shortcuts import get_object_or_404 from django.urls import reverse from django.core.validators import ValidationError from django.views.decorators.clickjacking import xframe_options_sameorigin def buildCommentList(cThread): cList = None if cThread and cThread.root_comment: current = cThread.root_comment if not current.hidden: cList = [ current ] while current.next: current = current.next if not current.hidden: if cList: cList.append(current) else: cList = [ current ] return cList @xframe_options_sameorigin def thread(request, thread_id): cThread = get_object_or_404(Thread, pk=thread_id) commentList = buildCommentList(cThread) template = loader.get_template('comments/thread.html') context = { 'thread': cThread, 'comments': commentList } return HttpResponse(template.render(context, request)) def checkMailAddr(addr): if "@" in addr: if addr[0] == "@": raise ValidationError("Invalid email address!") domain = addr.split("@")[1] if "." in domain and len(domain) >= 5: for i in domain.split("."): if len(i) < 2: raise ValidationError("Invalid email address!") return 1 else: raise ValidationError("Invalid email address!") else: raise ValidationError("Invalid email address!") def checkLength(name, x): if len(name) > x: return 1 else: raise ValidationError("Not enough characters in field!") @xframe_options_sameorigin def post(request, thread_id): cThread = get_object_or_404(Thread, pk=thread_id) template = loader.get_template('comments/thread.html') commentList = buildCommentList(cThread) context = {'thread': cThread, 'comments': commentList} if request.POST: name = request.POST['comment_author'] mail = request.POST['comment_author_email'] data = request.POST['comment_data'] try: validationCounter = 0 validationCounter += checkLength(name, 1) validationCounter += checkMailAddr(mail) validationCounter += checkLength(data, 8) except ValidationError: if validationCounter == 0: context['error_message'] = "What was your name again?" if validationCounter == 1: context['error_message'] = "Enter a valid e-mail address, please. It is only recorded for accountability; it is not publicized." if validationCounter == 2: context['error_message'] = "Say something meaningful! At least 8 characters are required for the comment field." return HttpResponse(template.render(context, request)) newComment = Comment(comment_author=name, comment_author_email=mail, comment_data=data) newComment.save() if cThread.root_comment: c = cThread.root_comment while c: last = c c = c.next last.next = newComment last.save() else: cThread.root_comment = newComment cThread.save() return HttpResponseRedirect(reverse('comments:thread', args=(thread_id,)))