Uncaught ReferenceError: load_posts не определен в <anonymous>:1:1
Я застрял на ошибке в своем коде. Я начинающий, работаю над проектом CS50 по веб-разработке4 - Сеть. Я пытаюсь заставить раздел "Все сообщения" отображать существующие сообщения от всех пользователей. Мой код на данный момент приведен ниже (и он неполный - я все еще работаю над ним). Мне кажется, что функция load_posts() не может быть запущена. Я хочу, чтобы она автоматически запускалась после загрузки DOM Content. Ничего не происходит автоматически после загрузки DOM COntent, поэтому я захожу в консоль и запускаю load_posts()( вручную, и она выдает ошибку: Uncaught ReferenceError: load_posts is not defined at :1:1.
models.py:
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
pass
class Profile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
followers = models.ManyToManyField(User, blank=True, related_name="followers")
following = models.ManyToManyField(User, blank=True, related_name="following")
def __str__(self):
return f"User profile for {self.user}"
class Post(models.Model):
poster = models.ForeignKey(User, on_delete=models.CASCADE, related_name="poster")
body = models.TextField(max_length=250)
timestamp = models.DateTimeField(auto_now_add=True, blank=True)
likes = models.ManyToManyField(Profile, blank=True, related_name="likes")
def __str__(self):
return f"{self.poster} posted '{self.body}' at {self.timestamp}. It has {self.likes} likes"
def serialize(self):
return {
"id": self.id,
"body": self.body,
"timestamp": self.timestamp.strftime("%b %#d %Y, %#I:%M %p"),
"likes": self.likes
}
urls.py:
from django.urls import path
from . import views
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("all_posts", views.all_posts, name="all_posts")
]
views.py:
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 .models import User, Post, Profile
def index(request):
if request.method == "POST":
post = request.POST["post-body"]
new_post = Post()
new_post.poster = request.user
new_post.body = post
new_post.save()
return render(request, "network/index.html")
else:
return render(request, "network/index.html")
def login_view(request):
if request.method == "POST":
# Attempt to sign user in
username = request.POST["username"]
password = request.POST["password"]
user = authenticate(request, username=username, password=password)
# Check if authentication successful
if user is not None:
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "network/login.html", {
"message": "Invalid username and/or password."
})
else:
return render(request, "network/login.html")
def logout_view(request):
logout(request)
return HttpResponseRedirect(reverse("index"))
def register(request):
if request.method == "POST":
username = request.POST["username"]
email = request.POST["email"]
# Ensure password matches confirmation
password = request.POST["password"]
confirmation = request.POST["confirmation"]
if password != confirmation:
return render(request, "network/register.html", {
"message": "Passwords must match."
})
# Attempt to create new user
try:
user = User.objects.create_user(username, email, password)
user.save()
except IntegrityError:
return render(request, "network/register.html", {
"message": "Username already taken."
})
login(request, user)
#auto-create a profile for new user
new_profile = Profile()
new_profile.user = user
new_profile.save()
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "network/register.html")
def all_posts(request):
posts = Post.objects.all()
posts = posts.order_by("-timestamp").all()
return JsonResponse([post.serialize() for post in posts], safe=False)
layout.html:
<!DOCTYPE html>
<html lang="en">
<head>
<title>{% block title %}Social Network{% endblock %}</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link href="{% static 'network/styles.css' %}" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Network</a>
<div>
<ul class="navbar-nav mr-auto">
{% if user.is_authenticated %}
<li class="nav-item">
<a class="nav-link" href="#"><strong>{{ user.username }}</strong></a>
</li>
{% endif %}
<li class="nav-item">
<a class="nav-link" href="{% url 'index' %}">All Posts</a>
</li>
{% if user.is_authenticated %}
<li class="nav-item">
<a class="nav-link" href="#">Following</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'logout' %}">Log Out</a>
</li>
{% else %}
<li class="nav-item">
<a class="nav-link" href="{% url 'login' %}">Log In</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'register' %}">Register</a>
</li>
{% endif %}
</ul>
</div>
</nav>
<div class="body">
{% block body %}
{% endblock %}
</div>
</body>
</html>
index.html:
{% extends "network/layout.html" %}
{% load static %}
{% block body %}
{% if user.is_authenticated %}
<h3>All Posts<h3>
<br>
<div id="new-post">
<h5>New Post</h5>
<form action="{% url 'index' %}" method="post">
{% csrf_token %}
<textarea class="form-control" name="post-body" placeholder="Type post here"></textarea>
<input id="post-message" type="submit" class="btn btn-primary"/>
</form>
</div>
<div id="all-posts">
</div>
{% else %}
<strong> Login To See Posts</strong>
{% endif %}
{% endblock %}
{% block script %}
<script src="{% static 'network/index.js' %}"></script>
{% endblock %}
index.js:
document.addEventListener('DOMContentLoaded', load_posts());
function load_posts() {
console.log("load_posts running")
document.querySelector('#all-posts').style.display = 'block';
fetch(`/all_posts`)
.then(response => response.json())
.then(posts => {
// Print posts
console.log(posts);
posts.forEach(post => show_posts(post));
});
}
function show_posts(post) {
//create 'main' div (will add content to it below), and store it in a variable
const post_display = document.createElement('div');
post_display.id = 'post';
post_display.className = 'row';
//create new div to display poster, add it to the 'main' div
const poster = document.createElement('div');
poster.id = 'post-poster';
poster.innerHTML = post.poster;
post_display.append(poster);
document.querySelector('#all-posts').append(post_display);
}