【问题标题】:Can't get JSON data on console无法在控制台上获取 JSON 数据
【发布时间】:2022-01-06 17:55:46
【问题描述】:

尝试在页面上呈现数据之前对数据进行控制台记录,但我不断收到 404 not found 或 not attributeName 'Porfile' 没有用户名作为属性。

对于 JSON,我是个菜鸟,我最近才开始弄乱它,请帮我做作业

JS:

$.ajax({
    type: 'GET',
    url: 'my-profile-json/',
    success: function(response){
        console.log(response);
    },
    error: function(error){
        console.log(error);
    }
});

网址:


from django.urls import path
from django.conf import settings
from django.conf.urls.static import static

from . import views
from .views import (
    post_view_json,
    profile_test_view,

    MyProfileView,
    MyProfileData,
)


urlpatterns = [
    path("", views.index, name="index"),
    path("login", views.login_view, name="login"),
    path("logout", views.logout_view, name="logout"),
    path("register", views.register, name="register"),
    path("test", profile_test_view, name="test"),
    path("my/", MyProfileView.as_view(), name="my-profile-view"),
    path("my-profile-json/", MyProfileData.as_view(), name="my-profile-json"),

    # endpoints
    path("posts-json/", post_view_json, name="posts-view-json")
]

观看次数

from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect
from django.http.response import JsonResponse
from django.shortcuts import render
from django.urls import reverse
from django.core import serializers

from .models import User, Post, Profile
from django.views.generic import TemplateView, View


class MyProfileData(View):
    def get(self, *args, **kwargs):
        profile = Profile.objects.get(user=self.request.user)
        qs = profile.get_proposals_for_following()
        profiles_to_follow_list = []
        for user in qs:
            p = Profile.objects.get(user__username=user.username)
            profile_item = {
                'id': p.id,
                'user': p.username,
                'avatar': p.avatar.url,
            }
            profiles_to_follow_list.append(profile_item)
        return JsonResponse({'pf_data': profiles_to_follow_list})

class MyProfileView(TemplateView):
    template_name = 'network/my_profile.html'

【问题讨论】:

    标签: javascript python json django ajax


    【解决方案1】:

    这里你使用 p.username 但它肯定应该是 p.user.username:

    profile_item = {
                    'id': p.id,
                    'user': p.username,
                    'avatar': p.avatar.url,
                }
    

    【讨论】:

      猜你喜欢
      • 2017-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多