如何在Django中按一下按钮?

2024-06-26 05:02:27 发布

您现在位置:Python中文网/ 问答频道 /正文

在视图.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)

在模型.py在

^{pr2}$

Tags: 用户py视图numberobjectsrequestcontextusername
1条回答
网友
1楼 · 发布于 2024-06-26 05:02:27

你可以在一个GET或POST上这样做。这是一个很简单的观点。在

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)

然后在你的网址.py您需要将以下内容添加到urlpatterns中。在

^{pr2}$

然后您需要使用一些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>

相关问题 更多 >