简体   繁体   English

从views.py获取JSON格式的当前登录用户

[英]Get current logged in user in JSON Format from views.py

I'm trying to build a follow and unfollow button, I want to show the button only For any other user who is signed in, a user should not be able to follow themselves.我正在尝试构建一个关注和取消关注按钮,我只想显示该按钮对于登录的任何其他用户,用户不应该能够关注自己。

How can I return from my views.py the currently logged-in user as a JSON format to my JS file?如何从我的views.py 将当前登录的用户以JSON 格式返回到我的JS 文件中? I'm building the button in the JavaScript file and not in the template, I tried to return as JSON format but didn't succeed我在 JavaScript 文件中而不是在模板中构建按钮,我试图以 JSON 格式返回但没有成功

views.py视图.py

def display_profile(request, profile):
    try:
        profile_to_display = User.objects.get(username=profile)
        profile_to_display_id = User.objects.get(pk=profile_to_display.id)
    except User.DoesNotExist:
        return JsonResponse({"error": "Profile not found."}, status=404)

    # Return profile contents
    if request.method == "GET":
        return JsonResponse(profile_to_display.profile.serialize(), safe=False)
    else:
        return JsonResponse({
            "error": "GET or PUT request required."
        }, status=400)

models.py模型.py

from django.contrib.auth.models import AbstractUser
from django.db import models


class User(AbstractUser):
    pass


class NewPost(models.Model):
    poster = models.ForeignKey("User", on_delete=models.PROTECT, related_name="posts_posted")
    description = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)
    likes = models.IntegerField(default=0)

    def serialize(self):
        return {
            "id": self.id,
            "poster": self.poster.username,
            "description": self.description,
            "date_added": self.date_added.strftime("%b %d %Y, %I:%M %p"),
            "likes": self.likes
        }


class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    following = models.ManyToManyField(User, blank=True, related_name="following")
    followers = models.ManyToManyField(User, blank=True, related_name="followers")

    def serialize(self):
        return {
            "profileID": self.user.id,
            "following": int(self.following.all().count()),
            "followers": int(self.followers.all().count()),
        }

index.js index.js

function load_user_info(user_clicked_on){
    document.querySelector('#page-view').style.display = 'none';
    document.querySelector('#posts-view').style.display = 'none';
    document.querySelector('#show-posts').style.display = 'none';
    document.querySelector('#load-profile').style.display = 'block';

    fetch(`/profile/${user_clicked_on}`)
        .then(response => response.json())
        .then(profile => {
            const profile_element = document.createElement('div');
            const followers = document.createElement('div');
            const following = document.createElement('div');
            const follow_button = document.createElement('button');
            followers.innerHTML = 'Followers: ' + profile.followers;
            following.innerHTML = 'Following: ' + profile.following;
            if (profile.profileID == ?? ){
               follow_button.innerHTML = 'Sameuser';
            }else{
                follow_button.innerHTML = 'Not same user';
            }
            profile_element.appendChild(followers);
            profile_element.appendChild(following);
            profile_element.appendChild(follow_button);
            profile_element.classList.add('profile_element');
            document.querySelector('#user-profile').appendChild(profile_element);
        });
    document.querySelector('#user-profile').innerHTML = `<h3>${user_clicked_on.charAt(0).toUpperCase() + user_clicked_on.slice(1)} Profile</h3>`;
}

I think all you need is the detail of the logged in user right?我认为您需要的只是登录用户的详细信息吗? may be you can get it from the request object by using可能您可以通过使用从请求 object 中获取它

{{request.user}}

this returns the logged user instance这将返回记录的用户实例

{{request.user.username}} {{request.user.email}}

this returns username and email这将返回用户名和 email

I dont know if you can directly use it in javascript, but you can kind of save this in template using a hidden field lik我不知道您是否可以直接在 javascript 中使用它,但是您可以使用隐藏字段将其保存在模板中

<input type="hidden" value="{{request.user.username}}" id='user_detail'>

and grab it using id selector (getElementById, or jquery)并使用 id 选择器(getElementById 或 jquery)抓取它

$('#user_detail').val()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM