Кнопка следует за пользователем должным образом, однако, когда кнопка переключается, чтобы отменить подписку, она переключается на все профили пользователей. Не следует за ними все, но кнопка переключается. Мне нужно поменять на JsonResponse / Ajax и вернуть.
ПОЛНЫЙ ПРОЕКТ ЗДЕСЬ: https://github.com/forafekt/save-live-set
Модели:
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
# from django.http import request
from config.settings import base
User = base.AUTH_USER_MODEL
class ProfileManager(models.Manager):
def toggle_follow(self, request_user, username_to_toggle):
profile_ = Profile.objects.get(user__username__iexact=username_to_toggle)
user = request_user
is_following = False
if user in profile_.followers.all():
profile_.followers.remove(user)
print("REMOVE FOLLOW") # testing
else:
profile_.followers.add(user)
is_following = True
print("ADD FOLLOW") # testing
return profile_, is_following
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
followers = models.ManyToManyField(User, related_name="is_following", blank=True)
activated = models.BooleanField(default=False)
objects = ProfileManager()
def __str__(self):
return str(self.user.username)
@receiver(post_save, sender=User)
def make_user_profile(sender, **kwargs):
if 'created' not in kwargs or not kwargs['created']:
return
# Assumes that the `OneToOneField(User)` field in "Profile" is named "user".
profile = Profile(user=kwargs["instance"])
# Set anything else you need to in the profile, then...
profile.save()`
Просмотров:
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import redirect, get_object_or_404
from django.views.generic import DetailView
from django.views.generic.base import View
from config.settings import base
from src.profiles.models import Profile
User = base.AUTH_USER_MODEL
class ProfileFollowToggle(LoginRequiredMixin, View):
def post(self, request, *args, **kwargs):
if request.method == "POST":
username_to_toggle = self.request.POST.get("username", None)
profile_, is_following = Profile.objects.toggle_follow(request.user, username_to_toggle)
try:
return redirect(f"/profile/{profile_.user.username}/")
except:
return HttpResponseRedirect(request.META.get('HTTP_REFERER')) # temp
class ProfileDetailView(DetailView):
template_name = "users/user_detail.html"
def get_object(self):
username = self.kwargs.get("username")
if username is None:
raise Http404
return get_object_or_404(User, username__iexact=username, is_active=True)
def get_context_data(self, *args, **kwargs):
context = super(ProfileDetailView, self).get_context_data(*args, **kwargs)
user = context['user']
is_following = False
if user.profile in self.request.user.is_following.all():
is_following = True
context['is_following'] = is_following
return context
URL:
from django.conf.urls import url
from src.profiles.views import ProfileFollowToggle
urlpatterns = (
#url(r"^$", ProfileFollowToggle, name="follow"), # FOR AJAX
url(r"^$", ProfileFollowToggle.as_view(), name="follow"), # FOR HTTP REDIRECT
)
Форма:
{% load static i18n %}
{% if user.is_authenticated %}
<form class="form" method="POST" action="{% url 'follow' %}" {% if request.user.username == object.username %} hidden {% endif %}>{% csrf_token %}
<input type="hidden" name="username" value="{% if request.user.username == object.username %}{{ username }}{% else %}{{ object.username }}{% endif %}">
<button
class="{% if request.user.is_following.filter %}btn btn-secondary{% else %}btn btn-primary{% endif %}">
{% if request.user.is_following.filter %}{% trans "Unfollow" %}{% else %}{% trans "Follow" %}{% endif %}
</button>
</form>
{% endif %}
Шаблон:
{% include 'users/includes/follow_form.html' with username=username is_following=is_following %}