From 3cb3cdfda10f3b46875304300f65648e53fd6171 Mon Sep 17 00:00:00 2001 From: tata Date: Thu, 10 Aug 2023 19:29:48 +0200 Subject: [PATCH] For #26 change name excpetion for more specific --- src/contacts/exceptions.py | 12 ++---------- src/contacts/tests/test_view.py | 10 +++++----- src/contacts/views.py | 6 +++--- src/profiles/exceptions.py | 8 ++++++++ src/profiles/views.py | 17 +++++++++-------- src/static/js/sendAvaForm.js | 19 ++++++++----------- src/static/js/utils.js | 4 ++-- src/templates/contacts/emails/letter.html | 14 ++++++-------- 8 files changed, 43 insertions(+), 47 deletions(-) diff --git a/src/contacts/exceptions.py b/src/contacts/exceptions.py index 4639ef9..afff3d7 100644 --- a/src/contacts/exceptions.py +++ b/src/contacts/exceptions.py @@ -24,17 +24,9 @@ class JobError(Exception): pass -class FailedNewsSubscription(Exception): +class HtmxFailureError(Exception): """ - get triggered if subscription to news letter failed - """ - - pass - - -class UnsubcribeFail(Exception): - """ - get triggered if subscription to news letter failed + get triggered if request is not htmx """ pass diff --git a/src/contacts/tests/test_view.py b/src/contacts/tests/test_view.py index 3afc2aa..dfebca9 100644 --- a/src/contacts/tests/test_view.py +++ b/src/contacts/tests/test_view.py @@ -4,7 +4,7 @@ from django.utils.translation import gettext_lazy as _ from src.accounts.tests.factories import UserFactory -from src.contacts.exceptions import FailedNewsSubscription, UnsubcribeFail +from src.contacts.exceptions import HtmxFailureError from src.profiles.models import Profile from src.profiles.tests.factories.profile_factory import ProfileFactory @@ -36,7 +36,7 @@ def test_failed_subscription_news(self): profile = user.profile self.client.force_login(user) url = reverse("contacts:subscribe") - with self.assertRaises(FailedNewsSubscription) as e: + with self.assertRaises(HtmxFailureError) as e: self.client.post(url) # noqa profile.refresh_from_db() @@ -54,7 +54,7 @@ def test_ok_unsubscribe(self): url = reverse("contacts:end_news", kwargs={"uuid": profile.uuid}) resp = self.client.post(url, **headers) profile.refresh_from_db() - print(resp.items()) + self.assertEqual(resp.status_code, 200) self.assertIsNotNone(resp.headers["HX-Redirect"]) self.assertFalse(profile.want_news) @@ -66,9 +66,9 @@ def test_failed_unsubscribe_no_htmx(self): """ profile = ProfileFactory(want_news=True) url = reverse("contacts:end_news", kwargs={"uuid": profile.uuid}) - with self.assertRaises(UnsubcribeFail) as e: - self.client.post(url) # noqa + with self.assertRaises(HtmxFailureError) as e: + self.client.post(url) # noqa self.assertTrue(profile.want_news) self.assertEqual( str(e.exception), (_("Something went wrong.Can't unsubscribe.")) diff --git a/src/contacts/views.py b/src/contacts/views.py index 99ee83e..951c664 100644 --- a/src/contacts/views.py +++ b/src/contacts/views.py @@ -7,7 +7,7 @@ from src.profiles.models import Profile -from .exceptions import FailedNewsSubscription, UnsubcribeFail +from .exceptions import HtmxFailureError class Subscribe(LRM, View): @@ -38,7 +38,7 @@ def post(self, request, **kwargs): headers={"HX-Redirect": "/"}, ) elif htmx_req is None: - raise FailedNewsSubscription(_("Subscription failed")) + raise HtmxFailureError(_("Subscription failed")) class UnSubscribe(View): @@ -68,4 +68,4 @@ def post(self, request, **kwargs): }, ) elif htmx_req is None: - raise UnsubcribeFail(_("Something went wrong.Can't unsubscribe.")) + raise HtmxFailureError(_("Something went wrong.Can't unsubscribe.")) diff --git a/src/profiles/exceptions.py b/src/profiles/exceptions.py index 4d4e398..8f2330d 100644 --- a/src/profiles/exceptions.py +++ b/src/profiles/exceptions.py @@ -4,3 +4,11 @@ class ProfileException(Exception): """ pass + + +class NoAjaxError(Exception): + """ + get triggered if request is not ajax + """ + + pass diff --git a/src/profiles/views.py b/src/profiles/views.py index ce7fe2c..679bfdf 100644 --- a/src/profiles/views.py +++ b/src/profiles/views.py @@ -2,8 +2,10 @@ from django.contrib.auth.mixins import LoginRequiredMixin as LRM from django.http import JsonResponse from django.shortcuts import get_object_or_404, redirect, render +from django.utils.translation import gettext_lazy as _ from django.views.generic import View +from .exceptions import NoAjaxError from .forms import ProfileForm from .models import Profile @@ -17,16 +19,15 @@ def get(self, request, **kwargs): return render(request, "profiles/profile_detail.html", ctx) def post(self, request, **kwargs): - # htmx_based + # ajax request + # request.headers.get("x-requested_with") == "XMLHttpRequest") # bug TODO: if user (avatar +) by chance click on upload without attached file # user contradicts themselves problem; - try: + ajax = request.headers.get("x-requested_with") + if ajax == "XMLHttpRequest": uuid = kwargs.get("uuid") profile = get_object_or_404(Profile, uuid=uuid) form = ProfileForm(request.POST, request.FILES, profile) - # if request.headers.get("x-requested_with") == "XMLHttpRequest": - # print("got an ajax") - if form.is_valid(): ava_img = form.cleaned_data.get("avatar") if ava_img: @@ -34,11 +35,11 @@ def post(self, request, **kwargs): else: profile.avatar = None profile.save() - return JsonResponse({"status_code": 200, "resp": "upload success"}) + return JsonResponse({"status_code": 200, "resp": "OK"}) else: return JsonResponse({"status_code": 404, "err": form.errors}) - except Exception as e: - print("exeption", e) + else: + raise NoAjaxError(_("Something went wrong")) class ProfileDelete(LRM, View): diff --git a/src/static/js/sendAvaForm.js b/src/static/js/sendAvaForm.js index 70abe8e..1fb1644 100644 --- a/src/static/js/sendAvaForm.js +++ b/src/static/js/sendAvaForm.js @@ -1,27 +1,24 @@ const sendAvaUpdate = function(url,avatar) { - let log = console.log; - const fd = new FormData(); + const fd = new FormData(); fd.append("csrfmiddlewaretoken",getCookie("csrftoken")); fd.append('avatar',avatar) fetch(url,{ method:"POST", - body:fd + body:fd, + headers:{"X-Requested-With": "XMLHttpRequest"}, }).then((resp)=>resp.json()) .then((data)=>{ - log(data); - if(data.status_code ===200){ - log("data",data.resp); - log("reloading") - window.location.reload(); + if(data.status_code ===200){ + setTimeout( + window.location.reload(),3000 + ) } else if(data.status_code ===404){ - log("code 404; upload failed") jsErr.classList.remove("visually-hidden"); jsErr.textContent = "Failed upload avatar"; data.err.avatar.forEach((err)=>{ let div = document.createElement("div") div.classList.add("errorlist"); - print("div is ",div) div.innerHTML = `${err}`; errDiv.appendChild(div) }); @@ -29,6 +26,6 @@ const sendAvaUpdate = function(url,avatar) { } }) .catch((err)=>{ - log(err["message"]); + console.log(err["message"]); }) } diff --git a/src/static/js/utils.js b/src/static/js/utils.js index a5c90f8..e662f0e 100644 --- a/src/static/js/utils.js +++ b/src/static/js/utils.js @@ -53,7 +53,7 @@ let helpUtil = (url,name)=>{ let arr = url.split(",") let mime = arr[0].match(/:(.*?);/)[1] - log("initial mime is ",mime,"check below ...") + console.log("initial mime is ",mime,"check below ...") let dataStr = arr.at(-1) // let dataStr = arr[1] let bstr = atob(dataStr); @@ -63,7 +63,7 @@ let helpUtil = (url,name)=>{ u8arr[lenData]= bstr.charCodeAt(lenData); } const file = new File([u8arr],name,{type:mime}) - log("final file ext is ",mime) + console.log("final file ext is ",mime) // console.log("w,h do not exist") return file; } diff --git a/src/templates/contacts/emails/letter.html b/src/templates/contacts/emails/letter.html index 13a4827..8f6aabd 100644 --- a/src/templates/contacts/emails/letter.html +++ b/src/templates/contacts/emails/letter.html @@ -12,15 +12,13 @@

Greetings from MedSandbox

Here is a link to read a new article: {% if posts %} {% for post in posts %} - Post title: {{post.title}} - {% comment %} - Some post

- {% endcomment %} - {% endfor%} - {% else %} -

No posts

- {% endif %} + {{post.title}} +

+ {% endfor%} + {% else %} +

No posts

{% endif %} + {% endif %}

Best regards,

Admin