Django URL 在模板中无法正常工作
我正在制作社交网络网站,用户可以在其中发布并喜欢该帖子。在我的一个模板上,由于路径不正确,心脏图像(表示帖子是否被喜欢)未加载:这是错误的:other_profile/static/network/nolike.png。它应该是:static/network/nolike.png。 other_profile 是我的模板的名称和路径。在我的网站上进行其他 API 获取调用时也会发生同样的情况。 URL 不应以 other_profile 开头。并且这种情况仅发生在 other_profile HTML 页面上。 代码:
urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("profile", views.profile, name="profile"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("Post/<str:post_id>", views.likes, name="likes"),
path("follows/<str:user_id>", views.follows, name="follows"),
path("following", views.following, name="following"),
path("other_profile/<str:user_id>", views.other_profile, name="other_profile")
]
views.py snippet
import json
from urllib.request import Request
from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect, render
from django.urls import reverse
from .forms import NewPostForm, likeForm, followForm
from .models import User, Post, Likes, Follows
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.core.exceptions import ObjectDoesNotExist
from datetime import datetime
def other_profile(request, user_id):
followform = followForm(request.POST or None)
if request.method == "POST":
try:
Follows.objects.filter(following__in=[user_id]).get(following=request.user).delete()
except Follows.DoesNotExist:
if followform.is_valid():
follows = followform.save(commit=False)
follows.user = User.objects.get(id=user_id)
follows.save()
follows.following.add(request.user)
posts = Post.objects.filter(user = user_id).order_by('-date')
return render(request, "network/otherprofile.html", {
"posts":posts, "followform":followform})
otherprofile.html
{% extends "network/layout.html" %}
{% block body %}
TODO
{% if user.is_authenticated %}
<form method="POST">{% csrf_token %}
{{ followform }}
<button id="follow">Follow</button>
</form>
<div id="posts">
{% for post in posts %}
<a href="{% url 'other_profile' post.user.id %}">{{ post.user.username }}</a>
<div class="name" id = "{{ post.user.id }}"><div>{{ post.date }}</div>{{ post.post }}</div>
<div id ="heart"></div>
{% endfor %}
</div>
{% endif %}
<script>
document.querySelector("#follow").addEventListener('click', () => {
var requestfollow = new Request(
`follows/${document.querySelector(".name").id}`,
{
method: 'POST',
}
);
fetch(requestfollow).then((response) => response.json()).then((data) => {
if (data.user_id == post.user.id) {
document.querySelector("#follow").innerHTML="Unfollow"
}})})
</script>
{% endblock %}
js file
document.addEventListener('DOMContentLoaded', function() {
var heart = new Image();
heart.id = "main";
heart.style.animationPlayState = 'paused';
var allButtons = document.querySelector('#posts').childElementCount;
var content = document.querySelectorAll('.name');
var button = document.querySelectorAll('#heart');
var csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
for (i = 0; i < allButtons / 2 - 1; i++) {
function listen(i) {
var requestPOST = new Request(
`/Post/${content[i].id}`,
{
method: 'POST',
headers: {'X-CSRFToken': csrftoken},
mode: 'same-origin' // Do not send CSRF token to another domain.
}
);
var requestGET = new Request(
`/Post/${content[i].id}`,
{
method: 'GET',
}
);
var heart = new Image();
heart.style.animationPlayState = 'paused';
heart.id = "main";
fetch(requestGET).then((response) => response.json()).then((data) => {
console.log(data.like)
if (data.like == true) {
heart.src = "static/network/like.png"
}
else{
heart.src = "static/network/nolike.png"
}
button[i].appendChild(heart);
})
button[i].addEventListener('click', () =>
fetch(requestPOST).then((response) => {
if (response.ok) {
response.json().then((data) => {
console.log(data.like)
if (data.like == true) {
heart.src = "static/network/like.png"
}
else{
heart.src = "static/network/nolike.png"
}
button[i].appendChild(heart);
heart.style.animationPlayState = 'running';
})}
else {
api(i)
console.log("not ok")
}}))}listen(i)}})
我在静态文件中也有一个js文件。如果需要的话请告诉我。 帮助将不胜感激!
I am making social network website where user can post and like the post. On one of my templates, image of heart (which represents if post is liked or not) is not loading because of incorrect path: this is the incorrect one: other_profile/static/network/nolike.png. It should be: static/network/nolike.png. other_profile is the name and path of my template. Same happens in case of other API fetch calls on my website. URL should not begin with other_profile. And this happens only on other_profile HTML page.
The code:
urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("profile", views.profile, name="profile"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("Post/<str:post_id>", views.likes, name="likes"),
path("follows/<str:user_id>", views.follows, name="follows"),
path("following", views.following, name="following"),
path("other_profile/<str:user_id>", views.other_profile, name="other_profile")
]
views.py snippet
import json
from urllib.request import Request
from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect, render
from django.urls import reverse
from .forms import NewPostForm, likeForm, followForm
from .models import User, Post, Likes, Follows
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.core.exceptions import ObjectDoesNotExist
from datetime import datetime
def other_profile(request, user_id):
followform = followForm(request.POST or None)
if request.method == "POST":
try:
Follows.objects.filter(following__in=[user_id]).get(following=request.user).delete()
except Follows.DoesNotExist:
if followform.is_valid():
follows = followform.save(commit=False)
follows.user = User.objects.get(id=user_id)
follows.save()
follows.following.add(request.user)
posts = Post.objects.filter(user = user_id).order_by('-date')
return render(request, "network/otherprofile.html", {
"posts":posts, "followform":followform})
otherprofile.html
{% extends "network/layout.html" %}
{% block body %}
TODO
{% if user.is_authenticated %}
<form method="POST">{% csrf_token %}
{{ followform }}
<button id="follow">Follow</button>
</form>
<div id="posts">
{% for post in posts %}
<a href="{% url 'other_profile' post.user.id %}">{{ post.user.username }}</a>
<div class="name" id = "{{ post.user.id }}"><div>{{ post.date }}</div>{{ post.post }}</div>
<div id ="heart"></div>
{% endfor %}
</div>
{% endif %}
<script>
document.querySelector("#follow").addEventListener('click', () => {
var requestfollow = new Request(
`follows/${document.querySelector(".name").id}`,
{
method: 'POST',
}
);
fetch(requestfollow).then((response) => response.json()).then((data) => {
if (data.user_id == post.user.id) {
document.querySelector("#follow").innerHTML="Unfollow"
}})})
</script>
{% endblock %}
js file
document.addEventListener('DOMContentLoaded', function() {
var heart = new Image();
heart.id = "main";
heart.style.animationPlayState = 'paused';
var allButtons = document.querySelector('#posts').childElementCount;
var content = document.querySelectorAll('.name');
var button = document.querySelectorAll('#heart');
var csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
for (i = 0; i < allButtons / 2 - 1; i++) {
function listen(i) {
var requestPOST = new Request(
`/Post/${content[i].id}`,
{
method: 'POST',
headers: {'X-CSRFToken': csrftoken},
mode: 'same-origin' // Do not send CSRF token to another domain.
}
);
var requestGET = new Request(
`/Post/${content[i].id}`,
{
method: 'GET',
}
);
var heart = new Image();
heart.style.animationPlayState = 'paused';
heart.id = "main";
fetch(requestGET).then((response) => response.json()).then((data) => {
console.log(data.like)
if (data.like == true) {
heart.src = "static/network/like.png"
}
else{
heart.src = "static/network/nolike.png"
}
button[i].appendChild(heart);
})
button[i].addEventListener('click', () =>
fetch(requestPOST).then((response) => {
if (response.ok) {
response.json().then((data) => {
console.log(data.like)
if (data.like == true) {
heart.src = "static/network/like.png"
}
else{
heart.src = "static/network/nolike.png"
}
button[i].appendChild(heart);
heart.style.animationPlayState = 'running';
})}
else {
api(i)
console.log("not ok")
}}))}listen(i)}})
I also have a js file in static files. If that is needed let me know.
Help would be greatly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以斜杠“/”开头。或者更好:
with the slash "/" at the beginning. Or better:
django 处理静态文件的方法是使用 static 标签
,但请注意在 settings.py 中设置静态内容
https://docs.djangoproject.com/en/4.0/howto/static -文件/
the django way of handling static files is to use the static tag
but please be aware to setup static stuff in settings.py
https://docs.djangoproject.com/en/4.0/howto/static-files/