简体   繁体   中英

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

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

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

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

{{request.user}}

this returns the logged user instance

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

this returns username and 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

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

and grab it using id selector (getElementById, or jquery)

$('#user_detail').val()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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