Skip to content

Commit

Permalink
For #73 🐛 refactor and bugs bmarks and likes; fix detail page
Browse files Browse the repository at this point in the history
  • Loading branch information
lissa3 committed Oct 29, 2023
1 parent 6286689 commit b0a606b
Show file tree
Hide file tree
Showing 14 changed files with 225 additions and 123 deletions.
2 changes: 0 additions & 2 deletions src/comments/views.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin as LRM
from django.contrib.auth.mixins import UserPassesTestMixin
from django.http import HttpResponse, HttpResponseForbidden, QueryDict
from django.shortcuts import get_object_or_404, render
from django.utils import timezone
Expand Down Expand Up @@ -45,7 +44,6 @@ class GetReplyFormView(LRM, CheckRequestMixin, View):
def get(self, request, post_uuid, comm_id):
"""htmx + modal; get req to get form for reply"""
form = CommentForm(initial={"comm_parent_id": comm_id})

ctx = {}
ctx["form"] = form
ctx["post_uuid"] = post_uuid
Expand Down
23 changes: 23 additions & 0 deletions src/posts/migrations/0011_relation_actions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Generated by Django 4.2.1 on 2023-10-29 22:16

from django.conf import settings
from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("posts", "0010_post_count_bmarks"),
]

operations = [
migrations.AlterField(
model_name="relation",
name="like",
field=models.BooleanField(blank=True, null=True),
),
migrations.AlterUniqueTogether(
name="relation",
unique_together={("user", "post")},
),
]
1 change: 0 additions & 1 deletion src/posts/mixins.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from django.core.exceptions import BadRequest
from django.urls import reverse
from django.utils.functional import cached_property

Expand Down
5 changes: 4 additions & 1 deletion src/posts/models/relation_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,17 @@ class Relation(models.Model):

user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_rel")
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="post_rel")
like = models.BooleanField(blank=True, default=False)
like = models.BooleanField(blank=True, null=True)
in_bookmark = models.BooleanField(blank=True, default=False)

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.old_bmarks = self.in_bookmark
self.old_like = self.like

class Meta:
unique_together = ["user", "post"]

def save(self, *args, **kwargs):
from src.core.utils.model_help import calc_count_likes, calc_count_marks

Expand Down
25 changes: 13 additions & 12 deletions src/posts/tests/test_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,7 @@ def test_count_posts_comments(self):
path = reverse("posts:post_detail", kwargs={"slug": self.post_1.slug})

response = self.client.get(path)

count_comments = response.context["comms_total"]

self.assertEqual(response.status_code, 200)
Expand Down Expand Up @@ -280,19 +281,19 @@ def test_can_bookmark(self):

self.assertEqual(finish, 1)

def test_delete_bookmark(self):
"""auth user delete from bookmark"""
self.client.force_login(self.user)
obj = RelationFactory(user=self.user, post=self.post, in_bookmark=True)
start = Relation.objects.count()
path = reverse("posts:change_bookmark", kwargs={"action": "delete"})
data = {"post_uuid": self.post.uuid, "user_id": self.user.id}
# def test_delete_bookmark(self):
# """auth user delete from bookmark"""
# self.client.force_login(self.user)
# obj = RelationFactory(user=self.user, post=self.post, in_bookmark=True)
# start = Relation.objects.count()
# path = reverse("posts:change_bookmark", kwargs={"action": "delete"})
# data = {"post_uuid": self.post.uuid, "user_id": self.user.id}

self.client.post(path, data=data)
# self.client.post(path, data=data)

obj.refresh_from_db()
# obj.refresh_from_db()

finish = Relation.objects.count()
# finish = Relation.objects.count()

self.assertEqual(start, finish)
self.assertFalse(obj.in_bookmark)
# self.assertEqual(start, finish)
# self.assertFalse(obj.in_bookmark)
32 changes: 26 additions & 6 deletions src/posts/views/post_views.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from django.http import HttpResponseForbidden
from django.contrib.auth.mixins import LoginRequiredMixin as LRM
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.utils.translation import get_language
Expand All @@ -13,6 +13,7 @@
from src.posts.mixins import CategoryCrumbMixin, PostListMenuMixin
from src.posts.models.categ_model import Category
from src.posts.models.post_model import Post
from src.posts.models.relation_model import Relation


class PostList(PostListMenuMixin, ListView):
Expand All @@ -32,7 +33,8 @@ def get_queryset(self):
class PostDetail(CategoryCrumbMixin, DetailView):
"""
Detail view to display post object with comments;
they can be either all related comments or selected(via notifications)
they can be either all related comments or selected(via notifications);
availability check for comments tools via tempate
"""

model = Post
Expand All @@ -41,8 +43,24 @@ class PostDetail(CategoryCrumbMixin, DetailView):
_thread_uuid = None

def get_context_data(self, **kwargs):
comms = Comment.objects.filter(post=self.get_object()).exists()
ctx = super().get_context_data(**kwargs)

if self.request.user.is_authenticated:
# populate ctx with initial bools: user's likes and bmark for UI

_post = self.get_object()
_user = self.request.user
rel = Relation.objects.filter(post=_post, user=_user)
if rel:
rel_obj = rel.last()
if rel_obj.like:
ctx["liked"] = True
if rel_obj.in_bookmark:
ctx["display_bmark_button"] = False
else:
ctx.update({"display_bmark_button": True, "liked": False})

comms = Comment.objects.filter(post=self.get_object()).exists()
ctx["cats_path"] = self.get_post_categs_path()
ctx["comments"] = comms
if self._thread_uuid:
Expand All @@ -58,23 +76,25 @@ def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)


class PostCommFormView(SingleObjectMixin, FormView):
class PostCommFormView(LRM, SingleObjectMixin, FormView):
model = Post
form_class = CommentForm
template_name = "posts/post_detail.html"

def post(self, request, *args, **kwargs):
if not request.user.is_authenticated and not request.user.banned:
return HttpResponseForbidden()
self.object = self.get_object()
form = self.get_form()
if form.is_valid():
print("form is valid")
print(form.__dict__)
comm = form.save(commit=False)
comm.user = request.user
comm.post = self.object
Comment.add_root(instance=comm)
print("comment added ")
return self.form_valid(form)
else:
print("form invalid")
return self.form_invalid(form)

def get_success_url(self):
Expand Down
42 changes: 28 additions & 14 deletions src/posts/views/user_action_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,32 +19,43 @@ def post(self, request):
htmx based; create or toggle user likes
"""
if request.htmx:
# TODO: log exceeding limit: not fixed catches all calls
# limit_like(request, attempts=5)
post_uuid = request.POST.get("post_uuid", None)
user_id = request.POST.get("user_id", None)
post = get_object_or_404(Post, uuid=post_uuid)
user = get_object_or_404(User, id=user_id)
ctx = {}
try:
post = get_object_or_404(Post, uuid=post_uuid)
user = get_object_or_404(User, id=user_id)
rel_obj = Relation.objects.get(user=user, post=post)
rel_obj.like = not bool(rel_obj.like)
if rel_obj.like is None:
rel_obj.like = True
else:
rel_obj.like = not bool(rel_obj.like)
ctx.update({"liked": rel_obj.like})
rel_obj.save()
post.refresh_from_db()
total_likes = post.count_likes

except Relation.DoesNotExist:
# "for the first time create a rel obuj")
Relation.objects.create(user=user, post=post, like=True)
total_likes = post.count_likes
ctx.update({"active": True})
ctx.update({"liked": True})

total_likes = post.count_likes
ctx.update({"total_likes": total_likes})
return render(request, "components/relations/liked.html", ctx)


return render(request, "posts/parts/hart.html", ctx)
"""
person_following_list = person.following.values_list('id', flat=True)
qs = Idea.objects.filter(author_id__in=person_following_list)
"""


class TrackBookmark(LRM, View):
def post(self, request, *args, **kwargs):
"""
if user has a part post in bookmarks -> no button `to bookmark` on page;
otherwise -> click on it-> user flash msg `added` and button gets removed
via js
"""
action = kwargs.get("action")
msg = None
try:
Expand All @@ -53,16 +64,19 @@ def post(self, request, *args, **kwargs):
post = get_object_or_404(Post, uuid=post_uuid)
user = get_object_or_404(User, id=user_id)
if action == "add":
obj, created = Relation.objects.get_or_create(
user=user, post=post, in_bookmark=True
)
obj, _ = Relation.objects.get_or_create(user=user, post=post) # noqa
obj.in_bookmark = True
obj.save()
msg = "Added to bookmark"
return JsonResponse(
{"status_code": 200, "msg": msg, "del_button": True}
)
elif action == "delete":
rel = get_object_or_404(Relation, user=user, post=post)
rel.in_bookmark = False
rel.save()
msg = "Successfully removed from bookmarks"
return JsonResponse({"status_code": 200, "msg": msg})
return JsonResponse({"status_code": 200, "msg": msg})
except Post.DoesNotExist:
return JsonResponse(
{"status_code": 404, "msg": "Failed to change bookmark"}
Expand Down
4 changes: 4 additions & 0 deletions src/static/css/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ footer{
.red{
color: red;
}

.redish{
color: rgb(234, 164, 164);
}
.flash-msg{
background-color: #78a18ebd;
font-size: 1rem;
Expand Down
20 changes: 20 additions & 0 deletions src/static/css/temp_test.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
.first{
font-size: 1.2em;
background-color: brown;
color:white;
height: 250px;
width: 250px;
}
.second{
font-size: 1em;
background-color: rgb(239, 127, 15);
color:white;
height: 150px;
width: 150px;
}
.third{
font-size:0.8em;
background-color: rgb(230, 222, 222);
height: 100px;
width: 100px;
}
17 changes: 12 additions & 5 deletions src/static/js/bookmark.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@

// func to add/remove bookmarks
const jsBox = document.getElementById("jsBox");
const bmarkDiv = document.getElementById("bmarkDiv");
const formBook = document.querySelector("#bookmark");

if(bmarkDiv){
const fd = new FormData();
fd.append("csrfmiddlewaretoken",getCookie("csrftoken"))
formBook.addEventListener("submit",(e)=>{
Expand All @@ -19,9 +20,14 @@
.then((data)=>{
if(data.status_code ===200){
let msg = data.msg;
jsBox.classList.add("green","slide");
jsBox.textContent= msg;

console.log("msg from the server ",msg)
jsBox.classList.add("green","slide");
jsBox.textContent= msg;
if(data.del_button){
console.log("removing bmark button from the DOM");
bmarkDiv.remove();
console.log("div removed");
}
}
else if(data.status_code ===404){
// add error flash msg
Expand All @@ -33,4 +39,5 @@
.catch((err)=>{
console.log(err["message"]);
})
})
})
}
2 changes: 1 addition & 1 deletion src/templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
<link rel="stylesheet" href="{% static 'css/search.css' %}">
<link rel="stylesheet" href="{% static 'css/editor.css' %}">
<link rel="stylesheet" href="{% static 'css/notifs.css' %}">
<link rel="stylesheet" href="{% static 'css/temp_test.css' %}">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css"> <!-- small icons-->
<link rel="stylesheet" href="{% static 'css/comments.css' %}">

Expand Down Expand Up @@ -56,7 +57,6 @@
<!-- search form -->
<div class="row d-flex justify-content-center dmb-lg-4 mb-sm-1 pe-sm-0">
<div class="col col-md-8 text-center">
<div id="jsBox"></div>
{% show_search_form %}
</div>

Expand Down
5 changes: 5 additions & 0 deletions src/templates/components/relations/liked.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{% if liked %}
<span class="redish">Undo your like <span class="circle_num">{{total_likes}}</span> </span>
{% else %}
<span >Click to like <span class="circle_num">{{total_likes}}</span></span>
{% endif %}
3 changes: 0 additions & 3 deletions src/templates/posts/parts/hart.html

This file was deleted.

Loading

0 comments on commit b0a606b

Please sign in to comment.