Отображение выборки JavaScript для таблиц JsonResponse 2 в HTMLPython

Программы на Python
Ответить
Anonymous
 Отображение выборки JavaScript для таблиц JsonResponse 2 в HTML

Сообщение Anonymous »

Сейчас я изучаю JavaScript и пытаюсь отобразить данные из двух таблиц: профиля и сообщений профиля пользователя.
viewa.py

Код: Выделить всё

@csrf_exempt
@login_required
def profile(request, user_id):
try:
user = User.objects.get(pk=user_id)
prof = Profile.objects.get(user=user)
posts = Post.objects.filter(author=user)
except prof.DoesNotExist:
return JsonResponse({"error": "Author not found."}, status=404)

# Return profile contents
if request.method == "GET":
return JsonResponse({
"prof": prof.serialize(),
"posts": [post.serialize() for post in posts]
}, safe=False)

# Update follower
elif request.method == "PUT":
data = json.loads(request.body)
if data.get("follower") is not None:
prof.follower = data["follower"]
prof.save()
return HttpResponse(status=204)

# Profile must be via GET or PUT
else:
return JsonResponse({
"error": "GET or PUT request required."
}, status=400)
urls.py
path("profile/int:user_id",views.profile, name="profile")
Здесь это представление API
API
Я пытался отобразить данные в index.html с помощью JavaScript.
index.js

Код: Выделить всё

function load_profile(author_id) {
// Load posts list
fetch(`/profile/${author_id}`)
.then(response => response.json())
.then(prof => {
// Print profile
console.log(prof);

const content_profile = document.createElement('div');
content_profile.className = "content_profile";

const user = document.createElement('p');
user.innerHTML = `${prof.prof.user}`;

const followers = document.createElement('p');
followers.innerHTML = `Follower: ${prof.prof.followers}`;

const following = document.createElement('p');
following.innerHTML = `Following: ${prof.prof.following}`;

const a = document.createElement('a');
a.className = "btn btn-primary";
a.innerHTML = "Follow";

content_profile.append(user, followers, following, a);
document.querySelector('#profile').append(content_profile);
})
.then(datas => {
// Print datas
console.log(datas);

datas.forEach(data => {
const list_item = document.createElement('ul');
list_item.className = "list-group";

const data_author = document.createElement('li');
data_author.className = "list-group-item list-group-item-action";
data_author.innerHTML = data.data.author+" at "+data.data.timestamp+" say:";
data_author.addEventListener('click', () => load_profile(data.data.author_id));

const data_content = document.createElement('li');
data_content.className = "list-group-item";
data_content.innerHTML = data.data.content;

const data_like = document.createElement('li');
data_like.className = "list-group-item list-group-item-action";
data_like.innerHTML = data.data.like+" Likes";

list_item.append(data_author, data_content, data_like);
document.querySelector('#postbox').append(list_item);
})
})
}
index.html

Код: Выделить всё

{% extends "sinpage/layout.html" %}
{% load static %}

{% block body %}



{{ request.user.username }}


{{form.as_p}}







{% endblock %}

{% block script %}

{% endblock %}
Итак, данные профиля отображаются, а данные сообщений — нет. Я впервые показываю 2 данных с помощью JavaScript. Думаю, я делаю это неправильно? Любой указатель приветствуется. Спасибо.

Подробнее здесь: https://stackoverflow.com/questions/790 ... es-on-html
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»