Can't Add/Accept and Decline/Cancel Friend requests on Django - python

Able to Send Friend requests successfully but responding to the requests are an issue. When you press Accept to Add, the button is removed but the Friend isn't added or when you press Cancel to Decline, nothing happens.
Tried adding a forms
class Add_Friend(forms.ModelForm):
model = UserProfile
def add_friend(request, user_profile):
request.notification_set.get(type=Notification.FRIEND_REQUEST, sender=user_profile.user.username).delete()
request.friends.add(user_profile)
user_profile.friends.add(self)
request.friend_requests.remove(user_profile)
noti = Notification.objects.create(owner=user_profile, type=Notification.ACCEPTED_FRIEND_REQUEST, sender=self.user.username)
user_profile.notification_set.add(noti)
return self.friends.count()
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
first_name = models.CharField(blank=True, max_length=128)
friends = models.ManyToManyField('self', blank=True, related_name='friends')
friend_requests = models.ManyToManyField('self', blank=True, related_name='friend_requests')
def send_friend_request(self, user_profile):
self.friend_requests.add(user_profile)
noti = Notification.objects.create(owner=self, type=Notification.FRIEND_REQUEST, sender=user_profile.user.username)
self.notification_set.add(noti)
return self.friend_requests.count()
def add_friend(self, user_profile):
self.friend_requests.remove(user_profile)
self.notification_set.get(type=Notification.FRIEND_REQUEST, sender=user_profile.user.username).delete()
self.friends.add(user_profile)
user_profile.friends.add(self)
noti = Notification.objects.create(owner=user_profile, type=Notification.ACCEPTED_FRIEND_REQUEST, sender=self.user.username)
user_profile.notification_set.add(noti)
return self.friends.count()
def cancel_friend_request(self, user_profile):
self.friend_requests.remove(user_profile)
self.notification_set.get(type=Notification.FRIEND_REQUEST, sender=user_profile.user.username).delete()
noti = Notification.objects.create(owner=user_profile, type=Notification.DECLINED_FRIEND_REQUEST, sender=self.user.username)
user_profile.notification_set.add(noti)
return self.friend_requests.count()
def __str__(self):
return self.get_first_name()
#Takes you to the userprofile page
def get_absolute_url(self):
return "/users/{}".format(self.id)
#method_decorator(login_required, name='dispatch')
class SendFriendRequestView(View):
def get(self, request, *args, **kwargs):
profile_id = request.GET.get('profile_id')
requester_id = request.GET.get('requester_id')
target = UserProfile.objects.get(id=profile_id)
requester = UserProfile.objects.get(id=requester_id)
target.send_friend_request(requester)
message = 'Friend request to {} sent!'.format(target.visible_name)
messages.info(request, message)
return redirect('profile', username=target.user.username)
#method_decorator(login_required, name='dispatch')
class CancelFriendRequestView(View):
def cancel_friend_request(request, id):
if request.user.is_authenticated():
user = get_object_or_404(User, id=id)
frequest, created = FriendRequest.objects.filter(
from_user=request.user,
to_user=user).first()
frequest.delete()
return HttpResponseRedirect('/users')
#method_decorator(login_required, name='dispatch')
class AddFriendView(View):
def get(self, request, *args, **kwargs):
try:
profile_id = request.GET.get('profile_id')
requester_id = request.GET.get('requester_id')
target = UserProfile.objects.get(id=profile_id)
requester = UserProfile.objects.get(id=requester_id)
target.add_friend(requester)
message = 'Added friend {}!'.format(target.visible_name)
messages.info(request, message)
return redirect('friends', username=target.user.username)
except Exception as e:
print('Error: {}'.format(e))
url(r'^friend-request/send/(?P<id>[\w\-]+)/$', send_friend_request),
url(r'^friend-request/cancel/(?P<id>[\w\-]+)/$', cancel_friend_request),
url(r'^friend-request/accept/(?P<id>[\w\-]+)/$', accept_friend_request),
{% if user.userprofile in userprofile.friends.all %}
<form>
<button id="remove_friend" data-requesterid="{{user.userprofile.id}}" data-profileid="{{userprofile.id}}">
Remove friend
</button>
</form>
{% elif user.userprofile in userprofile.friend_requests.all %}
Friend request pending...
<form>
<button id="cancel_friend_request " data-requesterid="{{user.userprofile.id}}" data-profileid="{{userprofile.id}}">
Cancel
</button>
</form>
{% else %}
<form>
<button id="send_friend_request" data-requesterid="{{user.userprofile.id}}" data-profileid="{{userprofile.id}}">
Send friend request
</button>
</form>
{% endif %}
I'd like the User to be able to Accept/Decline Friend Requests.

Related

Django form not valid - not null constraint

I have been looking at this issue for quite a while now. My form just keeps being invalid.
model.py
class GroupMember(models.Model):
Groupname = models.ForeignKey(DareGroups, on_delete=models.CASCADE)
Username = models.ForeignKey(DareUser, on_delete=models.CASCADE)
IsAdmin = models.BooleanField(default=False)
#receiver(post_save, sender=DareGroups)
def create_GroupAdmin(sender, instance, created, **kwargs):
if created:
GroupMember.objects.create(Groupname=instance,Username=get_current_authenticated_user().dareuser,IsAdmin=True)
#print(instance)
def __str__(self):
return self.Groupname.Groupname + "_"+self.Username.Username.username
view.py
def index(request):
if request.user.is_authenticated==True:
print('we zijn hier 1')
if request.method == "POST":
print('we zijn hier 2')
if 'newgroup' in request.POST:
formgroup = GroupsForm(request.POST)
if formgroup.is_valid():
print('komen we dan hier?')
formgroup.save()
return redirect('index')
elif 'newchallenge' in request.POST:
formchallenge = NewChallengeForm(request.POST)
if formchallenge.is_valid():
formchallenge.save()
return redirect('index')
elif 'addmember' in request.POST:
formaddmember=AddMemberToGroupForm(request.POST)
print('we zijn hier 3')
print(formaddmember.data)
if formaddmember.is_valid():
print('we zijn hier 4')
formaddmember.save()
else:
print('we zijn hier 5')
formaddmember.save()
print(formaddmember.errors)
return redirect('index')
else:
formgroup = GroupsForm()
formchallenge=NewChallengeForm()
formaddmember=AddMemberToGroupForm()
return render(request,"DareU/index.html",{'formgroup':formgroup,'formchallenge':formchallenge,'formaddmember':formaddmember})
else:
return render(request,"DareU/index.html")
forms.py
class AddMemberToGroupForm(forms.ModelForm):
class Meta:
model = GroupMember
fields = ('Groupname', 'Username','IsAdmin')
def __init__(self, user=None, **kwargs):
super(AddMemberToGroupForm, self).__init__(**kwargs)
self.fields['Groupname'].queryset = DareGroups.objects.filter(groupmember__IsAdmin=True)
HTML
<div class='container has-text-left' id="myForm3">
<h2 class="title is-2">Add member to group</h2>
<form method="POST" class="post-form">
{% csrf_token %}
{{ formaddmember.as_p }}
<button type="submit" class="button is-small is-success" name="addmember">Save</button>
<button type="button" class="button is-small is-danger cancel" onclick="closeForm3()">Close</button>
</form>
</div>
So, I can't get passed the is_valid check. If I do try to just save, I get the following error:
NOT NULL constraint failed: DareU_groupmember.Username_id
The form is rendering fine. I can select the correct values for both groupname and username, but it seems like when posting the form, the values are somehow lost.
I think it's because you're not passing *args to super() and if you're passing extra kwargs in, make sure to pop them before calling super().
def __init__(self, *args, **kwargs):
super(AddMemberToGroupForm, self).__init__(*args, **kwargs)
self.fields['Groupname'].queryset = DareGroups.objects.filter(groupmember__IsAdmin=True)
So Harben got me on the right path, to take a look at the init method.
It works after re-writing it like this:
def __init__(self, *args, **kwargs):
super().__init__(*args,**kwargs)
self.fields['Groupname'].queryset = DareGroups.objects.filter(groupmember__IsAdmin=True)

Like button in django is not working properly in django

I have added like and dislike button to Song post When like object is not created if some click on like it is showing intigrity error if like object is already there then it is not rendering that to template.
models.py
Codes in models.py
class Song(models.Model):
song_title = models.CharField(max_length=25)
album = models.ForeignKey(Album, related_name='album_name', on_delete=models.CASCADE, blank=True)
singer = models.ManyToManyField(Singer, blank=True)
language = models.CharField(max_length=25)
class VoteManager(models.Manager):
def get_vote_or_unsaved_blank_vote(self,song,user):
try:
return Vote.objects.get(song=song,user=user)
except ObjectDoesNotExist:
return Vote(song=song,user=user)
class Vote(models.Model):
UP = 1
DOWN = -1
VALUE_CHOICE = ((UP, "👍️"),(DOWN, "👎️"),)
like = models.SmallIntegerField(choices=VALUE_CHOICE)
user = models.ForeignKey(User,on_delete=models.CASCADE)
song = models.ForeignKey(Song, on_delete=models.CASCADE)
voted_on = models.DateTimeField(auto_now=True)
objects = VoteManager()
class Meta:
unique_together = ('user', 'song')
views.py
Codes in views.py
class SongDetailView(DetailView):
model = Song
template_name = 'song/song_detail.html'
def get_context_data(self,**kwargs):
ctx = super().get_context_data(**kwargs)
if self.request.user.is_authenticated:
vote = Vote.objects.get_vote_or_unsaved_blank_vote(song=self.object, user = self.request.user)
if vote.id:
vote_url = reverse('music:song_vote_update', kwargs={'song_id':vote.song.id,'pk':vote.id})
else:
vote_url = reverse('music:song_vote_create', kwargs={'song_id':vote.song.id})
vote_form = SongVoteForm(instance=vote)
ctx['vote_form'] = vote_form
ctx['vote_url'] = vote_url
return ctx
class SongUpdateView(UpdateView):
form_class = SongVoteForm
queryset = Song.objects.all()
def get_object(self,queryset=None):
song = super().get_object(queryset)
user = self.request.user
return song
def get_success_url(self):
song_id = self.kwargs.get('song_id')
return reverse('music:song_detail', kwargs={'pk':song_id})
class SongVoteCreateView(View):
form_class = SongVoteForm
context = {}
def post(self,request,pk=None,song_id=None):
vote_obj,created = Vote.objects.get_or_create(pk=pk)
song_obj = Song.objects.get(pk=song_id)
vote_form = SongVoteForm(request.POST, instance=vote_obj)
if vote_form.is_valid():
new_vote = vote_form.save(commit=False)
new_vote.user = self.request.user
new_vote.song = song_obj
return redirect('/album/')
Song_detail.html
codes in song_detail.html
<form action="{{vote_url}}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ vote_form.as_p }}
<button class="btn btn-primary" type="submit" >Vote</button>
</form>
Error Code
This is the error when submitting the like button. Refer here for the traceback
NOT NULL constraint failed: album_vote.song_id
song and user fields are required. So you have to give song and user while creating Vote.
here is full code::
class SongVoteCreateView(View):
form_class = SongVoteForm
context = {}
def post(self,request,pk=None,song_id=None):
song_obj = Song.objects.get(pk=song_id)
vote_obj,created = Vote.objects.get_or_create(song = song_obj, user = request.user)
vote_form = SongVoteForm(request.POST, instance=vote_obj)
if vote_form.is_valid():
vote_form.save()
return redirect('/album/')
also in VoteManager, the code
return Vote(song=song,user=user)
won't create vote, instead you have to use
return Vote.objects.create(song=song,user=user)

Django form Validation error not showing up also the form is not authenticating

Outcome needed : My main aim is to get a guest login that is user adds email address and then django checks for the email in the database if it finds one then error is shown else user is logged in.
Problem : In my form when I add an email address then Django adds the email in the database but if I add that email again no error is shown also I am not being logged in Django.
Version Using:
appdirs==1.4.2
cffi==1.9.1
cryptography==1.7.2
Django==1.8.4
django-crispy-forms==1.6.1
django-registration-redux==1.4
enum34==1.1.6
idna==2.4
ipaddress==1.0.18
olefile==0.44
packaging==16.8
Pillow==4.0.0
pyasn1==0.2.3
pycparser==2.17
pyOpenSSL==16.2.0
pyparsing==2.1.10
requests==2.13.0
six==1.10.0
forms.py
from django import forms
from django.contrib.auth import get_user_model
User = get_user_model()
class GuestCheckoutForm(forms.Form):
email = forms.EmailField()
email2 = forms.EmailField(label='Verify Email')
def clean_email2(self):
email = self.cleaned_data.get("email")
email2 = self.cleaned_data.get("email2")
if email == email2:
user_exists = User.objects.filter(email=email).count()
if user_exists != 0:
raise forms.ValidationError("This User already exists. Please login instead.")
return email2
else:
raise forms.ValidationError("Please confirm emails are the same")
views.py
from django.contrib.auth.forms import AuthenticationForm
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, Http404, JsonResponse
from django.shortcuts import render, get_object_or_404, redirect
from django.views.generic.base import View
from django.views.generic.detail import SingleObjectMixin, DetailView
from django.views.generic.edit import FormMixin
# Create your views here.
from orders.forms import GuestCheckoutForm
from orders.models import UserCheckout
from products.models import Variation
from .models import Cart, CartItem
class ItemCountView(View):
def get(self, request, *args, **kwargs):
if request.is_ajax():
cart_id = self.request.session.get("cart_id")
if cart_id == None:
count = 0
else:
cart = Cart.objects.get(id=cart_id)
count = cart.items.count()
request.session["cart_item_count"] = count
return JsonResponse({"count": count})
else:
raise Http404
class CartView(SingleObjectMixin, View):
model = Cart
template_name = "carts/view.html"
def get_object(self, *args, **kwargs):
self.request.session.set_expiry(0) #5 minutes
cart_id = self.request.session.get("cart_id")
if cart_id == None:
cart = Cart()
cart.save()
cart_id = cart.id
self.request.session["cart_id"] = cart_id
cart = Cart.objects.get(id=cart_id)
if self.request.user.is_authenticated():
cart.user = self.request.user
cart.save()
return cart
def get(self, request, *args, **kwargs):
cart = self.get_object()
item_id = request.GET.get("item")
delete_item = request.GET.get("delete", False)
item_added = False
if item_id:
item_instance = get_object_or_404(Variation, id=item_id)
qty = request.GET.get("qty", 1)
try:
if int(qty) < 1:
delete_item = True
except:
raise Http404
cart_item, created = CartItem.objects.get_or_create(cart=cart, item=item_instance)
if created:
item_added = True
if delete_item:
cart_item.delete()
else:
cart_item.quantity = qty
cart_item.save()
if not request.is_ajax():
return HttpResponseRedirect(reverse("cart"))
#return cart_item.cart.get_absolute_url()
if request.is_ajax():
try:
total = cart_item.line_item_total
except:
total = None
try:
subtotal = cart_item.cart.subtotal
except:
subtotal = None
try:
cart_total = cart_item.cart.total
except:
cart_total = None
try:
tax_total = cart_item.cart.tax_total
except:
tax_total = None
try:
total_items = cart_item.cart.items.count()
except:
total_items = 0
data = {
"deleted": delete_item,
"item_added": item_added,
"line_total": total,
"subtotal": subtotal,
"cart_total": cart_total,
"tax_total": tax_total,
"total_items": total_items
}
return JsonResponse(data)
context = {
"object": self.get_object()
}
template = self.template_name
return render(request, template, context)
class CheckoutView(FormMixin, DetailView):
model = Cart
template_name = "carts/checkout_view.html"
form_class = GuestCheckoutForm
def get_object(self, *args, **kwargs):
cart_id = self.request.session.get("cart_id")
if cart_id == None:
return redirect("cart")
cart = Cart.objects.get(id=cart_id)
return cart
def get_context_data(self, *args, **kwargs):
context = super(CheckoutView, self).get_context_data(*args, **kwargs)
user_can_continue = False
user_check_id = self.request.session.get("user_checkout_id")
if not self.request.user.is_authenticated() or user_check_id == None:# or if request.user.is_guest:
context["login_form"] = AuthenticationForm()
context["next_url"] = self.request.build_absolute_uri()
elif self.request.user.is_authenticated() or user_check_id != None:
user_can_continue = True
else:
pass
context["user_can_continue"] = user_can_continue
context["form"] = self.get_form()
return context
def post(self, request, *args, **kwargs):
self.object = self.get_object()
form = self.get_form()
if form.is_valid():
email = form.cleaned_data.get("email")
user_checkout, created = UserCheckout.objects.get_or_create(email=email)
request.session["user_checkout_id"] = user_checkout.id
print user_checkout
return self.form_valid(form)
else:
return self.form_invalid(form)
def get_success_url(self):
return reverse("checkout")
checkout_view.html
{% extends "base.html" %}
{% load i18n %}
{% load crispy_forms_tags %}
{% block content %}
{% if not user_can_continue %}
<div class='col-sm-6'>
<p class='lead'>Continue as Guest</p>
<form method='POST' action=''>{% csrf_token %}
{{ form|crispy }}
<input type='submit' class='btn btn-success' value='Continue as Guest' />
</form>
</div>
<div class='col-sm-6'>
<p class='lead'>Login to Continue</p>
<form method='POST' action="{% url 'auth_login' %}"> {% csrf_token %}
{{ login_form|crispy }}
<input type='hidden' name='next' value='{{ next_url }}' />
<input type='submit' class='btn btn-success' value='Login' />
</form>
<p class='text-center'>
<p>{% trans "Forgot password" %}? {% trans "Reset it" %}!</p>
<p>{% trans "Not member" %}? {% trans "Register" %}!</p>
</p>
</div>
{% endif %}
{% endblock %}
models.py
from django.conf import settings
from django.db import models
# Create your models here.
class UserCheckout(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True) #not required
email = models.EmailField(unique=True) #--> required
def __unicode__(self): #def __str__(self):
return self.email
As such I am getting no error but the problems stated above are occurring
The clean_* methods in django should always return the value.
def clean_email2(self):
email = self.cleaned_data.get("email")
email2 = self.cleaned_data.get("email2")
if email == email2:
# Query your UserCheckout model. Not the auth one!
if UserCheckout.objects.filter(email=email).exists():
raise forms.ValidationError("This User already exists. Please login instead.")
else:
raise forms.ValidationError("Please confirm emails are the same")
return email2

user profile of other user shows up

The id of admin is 1 when i open the admin user at the admin panel. Likewise the id of michael is 2 but when i click the profile icon instead of showing me the profile of admin i get profile of michael. To get the id i have used user.id of the requested user.
Also the problem is i could not use slug in such model.
restaurant/base.html
{% if user.is_authenticated %}
<li class="nav-item">
<a class="nav-link user-icon" href="{% url 'userprofiles:profile' user.id %}">
<i class="fa fa-user"></i>
</a>
</li>
{% else %}
userprofiles/urls.py
urlpatterns = [
# url(r'^profile/(?P<profile_name>[-\w]+)/(?P<profile_id>\d+)/$', views.profile, name='profile'),
url(
r'^profile/(?P<profile_id>\d+)/$',
views.profile,
name='profile'
),
]
userprofiles/views.py
def profile(request, profile_id):
if profile_id is "0":
userProfile = get_object_or_404(UserProfile, pk=profile_id)
else:
userProfile = get_object_or_404(UserProfile, pk=profile_id)
user_restaurant = userProfile.restaurant.all()
user_order = userProfile.order_history.all()
total_purchase = 0
for ur in user_order:
total_purchase += ur.get_cost()
return render(
request,
'userprofiles/profile.html',
{
'userProfile':userProfile,
'user_restaurant':user_restaurant,
'user_order':user_order,
'total_purchase':total_purchase
}
)
userprofiles/profile.html
{% for user_restaurant in user_restaurant %}
{{user_restaurant.name}}<br/>
{{user_restaurant.address }}
{% endfor %}
userprofiles/models.py
class UserProfile(models.Model):
user = models.OneToOneField(User)
restaurant = models.ManyToManyField(Restaurant)
order_history = models.ManyToManyField(OrderMenu)
# favorites = models.ManyToManyField(Restaurant)
is_owner = models.BooleanField(default=False)
class Meta:
def __str__(self):
return self.user.username
# def get_absolute_url(self):
# return reverse('userprofiles:profile', kwargs={'slug':self.slug, 'id':self.id})
How can i use slug for such model so that in admin panel the slug for that user be automatically saved? Because there is no post method.
But the main problem is i am getting userprofile of another user.
Just add 1 everywhere you use profile_id
def profile(request, profile_id):
if profile_id is "0": # Is profile_id a string or integer?
userProfile = get_object_or_404(UserProfile, pk=(profile_id+1)) # What does this do?
else:
userProfile = get_object_or_404(UserProfile, pk=(profile_id+1))
user_restaurant = userProfile.restaurant.all()
user_order = userProfile.order_history.all()
total_purchase = 0
for ur in user_order:
total_purchase += ur.get_cost()
return render(request, 'userprofiles/profile.html', {'userProfile':userProfile,
'user_restaurant':user_restaurant,
'user_order':user_order,
'total_purchase':total_purchase })
I suspect that somewhere in your code you've got a n-1 problem (i.e. computers start counting at 0 but humans start counting at 1). I haven't found exactly where it is, but this will probably work as a bandage solution in the meantime.
Also, I'm not sure what that if does in your code, it looks like it would never get used if profile_id is an integer.
I used slug instead of id and for using slug i have used pre_save signal where slug value is taken from the username.
def profile(request, profile_slug):
if profile_slug is None:
userprofile = get_object_or_404(UserProfile,slug=profile_slug)
else:
userprofile = get_object_or_404(UserProfile, slug=profile_slug)
user_restaurant = userprofile.restaurant.all()
user_order = userprofile.order_history.all()
total_purchase = userprofile.total_purchase
return render(request, 'userprofiles/profile.html', {'userprofile':userprofile,
'user_restaurant':user_restaurant,
'user_order':user_order,
'total_purchase':total_purchase})
I filled the value of slug in this way.
def create_slug(instance, new_slug=None):
print('instance',instance.user)
slug = slugify(instance.user.username)
if new_slug is not None:
slug = new_slug
qs = UserProfile.objects.filter(slug=slug).order_by("-id")
exists = qs.exists()
if exists:
new_slug = "%s-%s" %(slug, qs.first().id)
return create_slug(instance, new_slug=new_slug)
return slug
def pre_save_post_receiver(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = create_slug(instance)
from django.db.models.signals import pre_save
pre_save.connect(pre_save_post_receiver, sender=UserProfile)

How to follow on a button click in Django?

Views.py - I want to be able to go to a users page, and then click and follow them from a button exactly like twitter, i sort of know how to add users as you can see by my add variable in my view but I really have not clue how to actually implement that into a button that allows me to follow the user! I have been stuck on this for a whole day and it may be very obvious so any help is greatly appreciated! I do not think my template is need for this question but if it is let me know!
#login_required
def home(request, username):
context = {}
if username == request.user.username:
return HttpResponseRedirect('/home /user/{0}'.format(request.user.username))
else:
user = User.objects.get(username=username)
user_profile = UserProfile.objects.filter(user=user)
following = user.userprofile.follows.all()
number = user.userprofile.follows.all().count()
tweet = Tweet.objects.filter(userprofile=user_profile).order_by('date')
yum = Tweet.objects.filter(userprofile=user_profile).count()
add = user.userprofile.follows.add(request.user.userprofile)
context['user'] = user
context['profile'] = user_profile
context['follow'] = following
context['number'] = number
context['tweet'] = tweet
context['yum'] = yum
return render (request, 'homer.html', context)
models.py
from django.db import models
from django.contrib.auth.models import User
import os
def get_image_path(instance, filename):
return os.path.join('photos', str(instance.user.id), filename)
class UserProfile(models.Model):
user = models.OneToOneField(User)
bio = models.CharField(max_length=120, blank=True, verbose_name='Biography')
follows = models.ManyToManyField('self', related_name='followers', symmetrical=False, blank=True)
theme = models.ImageField(upload_to=get_image_path, blank=True)
profile_picture = models.ImageField(upload_to=get_image_path, blank=True)
def __str__(self):
return self.bio
class Tweet(models.Model):
userprofile = models.ForeignKey(UserProfile)
tweets = models.TextField(max_length=120)
date = models.DateTimeField()
def __str__(self):
return self.tweets
You could do this on a GET or a POST. Here's the view it on a GET since that's simpler.
from django.http import JsonResponse
def follow_user(request, user_profile_id):
profile_to_follow = get_object_or_404(UserProfile, pk=user_profile_id)
user_profile = request.user.userprofile
data = {}
if profile_to_follow.follows.filter(id=user_profile.id).exists():
data['message'] = "You are already following this user."
else:
profile_to_follow.follows.add(user_profile)
data['message'] = "You are now following {}".format(profile_to_follow)
return JsonResponse(data, safe=False)
Then in your urls.py you'd need to add the following to your urlpatterns.
url(r'^follow/(?<user_profile_id>[\d]+)/$', views.follow_user)
Then you'd need to use some javascript like the following:
$('.follow-button').click(function() {
$.get($(this).data('url'), function(response) {
$('.message-section').text(response.message).show();
});
});
This assumes some html like the following:
<body>
<div class="message-section" style="display:none;"></div>
{% for user_profile in all_user_profiles %}
<button data-url="{% url "example_app.views.follow_user" user_profile_id=user_profile.id %}"
class="follow-button" type="button">Follow</button>
{% endfor %}
</body>

Categories