Igot
Igot

Reputation: 11

Get certain parameter on a fetch request

I'm developing a twitter-like app where users are able to make posts. I want to make a div containing the Username posting, the post content, and the date.

Since the username is a ForeignKey, I had some errors until I was able to fetch the whole User table.

I only need to get the username field, which seems to be a dictionary inside and list, as I'll show below.

Below, you may find the codes: The Models

class User(AbstractUser):
    pass

class PostData(models.Model):
    active = models.BooleanField(default=True) # In case I want to add a delete feature in the future
    post_content = models.CharField(max_length=360)
    date_post_created = models.DateTimeField(auto_now_add=True) 
    user_posting = models.ForeignKey(User, on_delete=models.CASCADE, related_name="userposting")

    def __str__(self):
        return f"{self.post_content}"

    def serialize(self):
        return {
            "post_content": self.post_content,
            "user_posting":serializers.serialize("json", User.objects.all()),
            "date_post_created": self.date_post_created
        }

The views.py

def all_posts(request):
    # Get posts.
    posts = PostData.objects.all()
    #Return in reverse chronological order
    posts = posts.order_by("-date_post_created").all()
    return JsonResponse([post.serialize() for post in posts], safe=False)

The posts.js (which has the code to feed the html)

function load_posts(){


    fetch('allposts')
    .then(response => response.json())
    .then(posts => {

        posts.forEach(element => {
            console.log(element.post_content);
            console.log(element.user_posting);
            console.log(element.date_post_created);

(...)

The current output:

from console.log(element.post_content); teste teste teste

** from console.log(element.user_posting); **

[ {"model": "network.user", "pk": 1, "fields": {"password": "pbkdf2_sha256$216000$C13hJOjD4ojv$AW5a0AFEisWO7IG0MkVNQ8k6+OnfN0CljEV8lnfEaKE=", "last_login": "2021-01-29T00:01:37.127Z", "is_superuser": false,
"username": "Igor", "first_name": "", "last_name": "", "email": "[email protected]", "is_staff": false, "is_active": true,
"date_joined": "2021-01-25T17:02:11.514Z", "groups": [],
"user_permissions": [] } } ]

from console.log(element.date_post_created); 2021-01-25T23:48:03.515Z

I want to extract the field username that in this case contains Igor. I've tried:

console.log(element.user_posting[0]['fields']['username']);

When I try:

console.log(element.user_posting[0].fields.username);

Got an error:

( Uncaught (in promise) TypeError: Cannot read property 'username' of undefined at posts.js:26 at Array.forEach (<anonymous>) at posts.js:23

Upvotes: 0

Views: 606

Answers (2)

Igot
Igot

Reputation: 11

Could you try to do let user = JSON.parse(element.user_posting[0]); console.log(user.fields.username); I guess the content of the array is a string and not already parsed as an object, so using JSON.parse() would make it an object. – user1453870 11 hours ago

Hey man, your answer was almost right, we just had to move the [0] out of the parse. The way it worked was:

let user = JSON.parse(element.user_posting);

console.log(user[0].fields.username);

Thanks everyone for your help :D

Upvotes: 1

Siva Sankar
Siva Sankar

Reputation: 1830

Django provides session user for default User model when logged in and anonymous user when logged out. I think you are not handling this case - when logged out. You can use @login_required decorator. So only loged in users can see your post.

from django.contrib.auth.decorators import login_required
    
@login_required
def all_posts(request):
    # Get posts.
    posts = PostData.objects.all()
    #Return in reverse chronological order
    posts = posts.order_by("-date_post_created").all()
    return JsonResponse([post.serialize() for post in posts], safe=False)

Upvotes: 0

Related Questions