Home > Software design >  Django URLs not working properly in template
Django URLs not working properly in template

Time:03-18

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  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!

CodePudding user response:

heart.src = "/static/network/like.png"

with the slash "/" at the beginning. Or better:

heart.src = "{% static 'network/like.png' %}"

CodePudding user response:

the django way of handling static files is to use the static tag

{% static 'network/nolike.png' %}

but please be aware to setup static stuff in settings.py https://docs.djangoproject.com/en/4.0/howto/static-files/

  • Related