Skip to content

Commit

Permalink
For #26 change name excpetion for more specific
Browse files Browse the repository at this point in the history
  • Loading branch information
lissa3 committed Aug 10, 2023
1 parent 6d1a5f7 commit 3cb3cdf
Show file tree
Hide file tree
Showing 8 changed files with 43 additions and 47 deletions.
12 changes: 2 additions & 10 deletions src/contacts/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
10 changes: 5 additions & 5 deletions src/contacts/tests/test_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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()
Expand All @@ -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)
Expand All @@ -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."))
Expand Down
6 changes: 3 additions & 3 deletions src/contacts/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

from src.profiles.models import Profile

from .exceptions import FailedNewsSubscription, UnsubcribeFail
from .exceptions import HtmxFailureError


class Subscribe(LRM, View):
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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."))
8 changes: 8 additions & 0 deletions src/profiles/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,11 @@ class ProfileException(Exception):
"""

pass


class NoAjaxError(Exception):
"""
get triggered if request is not ajax
"""

pass
17 changes: 9 additions & 8 deletions src/profiles/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -17,28 +19,27 @@ 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:
profile.avatar = ava_img
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):
Expand Down
19 changes: 8 additions & 11 deletions src/static/js/sendAvaForm.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,31 @@
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)
});
throw new Error(message="Custom error: upload failed");
}
})
.catch((err)=>{
log(err["message"]);
console.log(err["message"]);
})
}
4 changes: 2 additions & 2 deletions src/static/js/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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;
}
Expand Down
14 changes: 6 additions & 8 deletions src/templates/contacts/emails/letter.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,13 @@ <h3>Greetings from MedSandbox</h3>
<p>Here is a link to read a new article:
{% if posts %}
{% for post in posts %}
<a href="#">Post title: {{post.title}}</a>
{% comment %}
<a href="{{domain}}{% url 'posts:post_detail' letter.post.slug %}">Some post</a></p>
{% endcomment %}
{% endfor%}
{% else %}
<p>No posts</p>
{% endif %}
<a href="{{domain}}{% url 'posts:post_detail' letter.post.slug %}">{{post.title}}</a>
</p>
{% endfor%}
{% else %}
<p>No posts</p>
{% endif %}
{% endif %}
<p>Best regards,</p>
<p>Admin</p>
<hr>
Expand Down

0 comments on commit 3cb3cdf

Please sign in to comment.