Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

html - like button for a blog post in Django

Looked over a few posts on Stack, but don't appear to see an answer.

I am trying to get the blog post to send the like button as a notification. I currently have the comments working fine, i can comment on a blog and that will send a notification to the user who wrote the blog. I just cant appear to get the like button to notify.

The blog post can be accessed by the title, to show you the post-detail screen of the individual post. On there we have a like button which i would like to be pressed and notify correctly.

Thank you, i am a little experienced but still trying to gain a better understanding.

Models.py

from typing import cast
from django.contrib.auth.decorators import user_passes_test
from django.db import models
from django.db.models.deletion import CASCADE
from django.db.models.fields.related import ForeignKey
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
from django.db.models.signals import post_save, post_delete
from notifications.models import Notification


class Category (models.Model):
    named = models.CharField(max_length=100)
    
    def __str__(self):
        return self.named
    
    def get_absolute_url(self):
        return reverse('home') 


    
    
# Create your models here.
cat_new_choice = Category.objects.all().values_list('named', 'named')

# first BLOG table - TEST this is how you create it!
class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    category = models.CharField(choices=cat_new_choice, max_length=200,default='Onboarding')
    likes = models.ManyToManyField(User, related_name='blog_posts', blank=True)
    #user who created this post, then the user gets deleted - what happens to the post? this will delete his post as well
    
    def __str__(self):
        return self.title
    
    def total_likes(self):
        return self.likes.all().count()
 
    def get_absolute_url(self):
            return reverse('post-detail', kwargs={'pk': self.pk}) 


class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    pdf = models.FileField(upload_to='books/pdfs/')
    cover = models.ImageField(upload_to='books/covers/', null=True, blank=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

           
# override the delete function to delete the cover and pdf from the DB
    def delete(self, *args, **kwargs):
        self.pdf.delete()
        self.cover.delete()
        super().delete(*args, **kwargs)

# upload document based off address
class Address(models.Model):
    name = models.CharField(max_length=100)
    address = models.CharField(max_length=100)
    pdf = models.FileField(upload_to='verification/pdfs/')
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    date_added = models.DateTimeField(default=timezone.now)
    uploaded_doc = models.BooleanField(default=False, verbose_name="Click for managerial review")


    def __str__(self):
        return self.name

class Bank(models.Model):
    bank = models.CharField(max_length=100)
    pdf = models.FileField(upload_to='verification/direct_debit/pdfs/')
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    date_added = models.DateTimeField(default=timezone.now)
    uploaded_doc = models.BooleanField(default=False, verbose_name="Click for managerial review")


    def __str__(self):
        return self.bank

class Ident(models.Model):
    title = models.CharField(max_length=100)
    name = models.CharField(max_length=100)
    pdf = models.FileField(upload_to='pdfs/')
    cover = models.ImageField(upload_to='books/covers/', null=True, blank=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

           
# override the delete function to delete the cover and pdf from the DB
    def delete(self, *args, **kwargs):
        self.pdf.delete()
        self.cover.delete()
        super().delete(*args, **kwargs)

class Comment(models.Model):
    post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE)
    body = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE )

    def user_comment_post(sender, instance, *args, **kwargs):
        comment = instance
        post = comment.post
        text_preview = comment.body[:90]
        sender = comment.user

        notify = Notification(post=post, sender=sender, user=post.author, text_preview=text_preview, notification_type=2)
        notify.save()

    def user_delete_comment(sender, instance, *args, **kwargs):
            comment = instance
            post = comment.post
            sender = comment.user

            notify = Notification.objects.filter(post=post, user=post.author, sender=sender, notification_type=2)
            notify.delete()

class Likes(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_like')
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='post_likes')

    def user_liked_post(sender, instance, *args, **kwargs):
        like = instance
        post = like.post
        sender = like.user
        notify = Notification(post=post, sender=sender,user=post.user, notification_type=1)
        notify.save()

    def user_unlike_post(sender, instance, *args, **kwargs):
        like = instance
        post = like.post
        sender = like.user
        
        notify = Notification.objects.filter(post=post, sender=sender, notification_type=1)
        notify.delete()
#likes
post_save.connect(Likes.user_liked_post, sender=Likes)
post_delete.connect(Likes.user_unlike_post, sender=Likes)

#comments
post_save.connect(Comment.user_comment_post, sender=Comment)
post_delete.connect(Comment.user_comment_post, sender=Comment)

views.py

from django.db.models.query import QuerySet
from django.http.response import HttpResponseRedirect
from django.shortcuts import redirect, render, get_object_or_404
from django.db import models
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.models import User
from django.views.generic import (
    ListView,
    DetailView,
    CreateView,
    UpdateView,
    DeleteView,
    
)
from .models import Address, Bank, Category, Comment, Ident, Post # Create your views here.
from django.core.files.storage import FileSystemStorage
from .forms import AddForm, BankForm, BookForm, Book, IdentForm, CommentForm
from django.urls import reverse_lazy
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.template import loader
from django.http import HttpResponse
from django.urls import reverse


@login_required
def home(request):
    context = {
            #context will read request the posts above to display on the home page

        'posts': Post.objects.all(),
                # keyname: value

    }
    return render(request, 'blog/home.html', context)

def address_home(request):
    context = {
            #context will read request the posts above to display on the home page

        'addresses': Address.objects.all(),
                # keyname: value

    }
    return render(request, 'blog/onboarding.html', context) 




class PostListView(ListView):
    model = Post
    template_name = 'blog/home.html'  # <app>/<model>_<viewtype>.html
    context_object_name = 'posts'
    ordering = ['-date_posted']
    paginate_by = 5



class UserPostListView(ListView):
    model = Post
    template_name = 'blog/user_posts.html'  # <app>/<model>_<viewtype>.html
    context_object_name = 'posts'
    paginate_by = 5

    def get_queryset(self):  # if user exists, capture them in the usl
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return Post.objects.filter(author=user).order_by('-date_posted')
##### create a class based view on a single post review #####

# pass the total amount of likes through the post detail page
class PostDetailView(DetailView):
    model = Post
    template_name = "blog/post_detail.html"


    def get_context_data(self, *args, **kwargs):
        context = super(PostDetailView, self).get_context_data(*args, **kwargs)
        post = get_object_or_404(Post, id=self.kwargs['pk'])
        total_likes = post.total_likes()
        liked = False
        if post.likes.filter(id=self.request.user.id).exists():
            liked = True
        context["total_likes"] = total_likes
        context["liked"] = liked
      
        return context

#class based views used to display,edit and create blog posts
#list views, create views, edit views, update views
#mixin now means if you're not logged in you cant get to post an item, you will be redirected to the login page.
class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    # go create the url pattern

    fields = ['title', 'content', 'category']

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

class AddCommentView(CreateView):
    model = Comment
    template_name= 'blog/add_comment.html'
    # go create the url pattern

    fields = '__all__'

    def form_valid(self, form):
        form.instance.post_id = self.kwargs['pk']
        return super().form_valid(form)

    success_url = reverse_lazy('blog-home')



####UPDATE A POST####

class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Post
    fields = ['title', 'content']

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False

####Delete a post

class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
    model = Post
    success_url = '/'

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False

#send document to the media folder.
def onboarding(request):
  
    return render(request, 'blog/onboarding.html')

#address stuff




# Address & Bank test (add to this)
@login_required
def m_models(request):
    address_list = Address.objects.all()
    bank_list = Bank.objects.all()
    id_list = Ident.objects.all()
    return render(request, "blog/onboarding.html", {
        'Address': address_list,
        'Bank': bank_list,
        'Ident': id_list
     } 
     )


def delete_address(request, pk):
    if request.method =="POST":
        address = Address.objects.get(pk=pk)
        address.delete()
    return redirect('onboarding')

def delete_bank(request, pk):
    if request.method =="POST":
        bank = Bank.objects.get(pk=pk)
        bank.delete()
    return redirect('onboarding')

def upload_address(request):
    if request.method == "POST":
        form = AddForm(request.POST, request.FILES)
        if form.is_valid():
            instance = form.save(commit = False) #save it, but dont commit just yet
            

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...