How to monitor button click in Django?

Views.py - I want to be able to go to the user page and then click and follow them with a button just like twitter, I know how to add users as you can see from my add variable in mine but I really don't know how to implement this as a button that allows me to follow the user! I've been stuck on this all day long and it can be very obvious so any help is greatly appreciated! I don't think my template is needed for this question, but if so 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

      

+3


source to share


1 answer


You can do it on GET or POST. Here's a view of it on GET, since it's easier.

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 need to add the following to your urls.

url(r'^follow/(?<user_profile_id>[\d]+)/$', views.follow_user)

      



Then you will need to use some javascript like below:

$('.follow-button').click(function() {
    $.get($(this).data('url'), function(response) {
        $('.message-section').text(response.message).show();
    });
});

      

This assumes some html looks like this:

<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>

      

+2


source







All Articles