如何在Django中按下按钮?

时间:2015-08-06 00:51:55

标签: python django

Views.py - 我希望能够转到用户页面,然后从一个完全像twitter的按钮点击并关注它们,我知道如何添加用户,就像我在我的添加变量中看到的那样查看但我真的不知道如何将其实际实现为一个允许我关注用户的按钮!我已经被困在这一整天了,这可能非常明显,所以任何帮助都非常感谢!我不认为我的模板需要这个问题,但如果是让我知道的话!

@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

1 个答案:

答案 0 :(得分:2)

您可以在GET或POST上执行此操作。以下是GET上的观点,因为它更简单。

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)

然后在您的urls.py中,您需要将以下内容添加到您的网址模式中。

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

然后您需要使用以下一些javascript:

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

这假定某些html如下:

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