How can I add a link to another page of my site with Django. I am currently getting a Page not found error

Viewed 36

Disquaire\urls.py

from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from store import views

urlpatterns = [
    url(r'^$', views.index),
    url(r'^store/', include('store.urls')),
    url(r'^admin/', admin.site.urls),
]

store.urls.py

urlpatterns = [
    url(r'^$', views.listing, name='listing'), 
    url(r'^(?P<album_id>[0-9]+)/$', views.details, name="details"),
    url(r'^search/$',views.search,name='search'),

]

list.html

{% for album in albums %} 
    <div class="col-sm-4 text-center">
        <a href="/store/ {%   url 'details' album_id=album.id %}">
          <img class="img-responsive" src="{{ album.picture }}" alt="{{ album.title }}">
        </a>
        <h3><a href="/store/ {%   url 'details' album_id=album.id%}">{{ album.title }}</a></h3> 
        {% for artist in album.artists.all %}
            <p>{{ artist.name }}</p>
        {% endfor %}
    </div>
    {% if forloop.counter|divisibleby:3 %}<div class="clearfix"></div>{% endif %} 
{% endfor %}

views.py

def details(request, album_id):
   
    album = Albums.objects.get(pk=album_id)
    artists = " ".join([artist.name for artist in album.artists.all()])
    message = "Le nom de l'album est {}. Il a été écrit par {}".format(album.title, artists)
    return HttpResponse(message)

index.html

{% extends 'store\base.html' %}

{% block content %}
    {% include 'store\list.html' %}
{% endblock %}

This is the error I get Page not found

I have already tried many proposals from the site but nothing work, or maybe I didn't applied them well.I am new to Python and Django so I would appreciate all help.

1 Answers

You have written your urls in the manner /store/ {% url 'details' album_id=album.id %} for some reason. The url template tag will give you a relative url from the domain of your site, hence you don't have to prefix your url. Also you write src="{{ album.picture }}" here I assume picture is an image field? If so you should be writing src="{{ album.picture.url }}" instead. Hence change your template to:

{% for album in albums %} 
    <div class="col-sm-4 text-center">
        <a href="{% url 'details' album_id=album.id %}">
          <img class="img-responsive" src="{{ album.picture.url }}" alt="{{ album.title }}">
        </a>
        <h3><a href="{% url 'details' album_id=album.id%}">{{ album.title }}</a></h3> 
        {% for artist in album.artists.all %}
            <p>{{ artist.name }}</p>
        {% endfor %}
    </div>
    {% if forloop.counter|divisibleby:3 %}<div class="clearfix"></div>{% endif %} 
{% endfor %}
Related