【问题标题】:How can I add a link to another page of my site with Django. I am currently getting a Page not found error如何使用 Django 添加指向我网站的另一个页面的链接。我目前收到页面未找到错误
【发布时间】:2021-08-29 15:51:03
【问题描述】:

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 %}

这是我得到的错误 Page not found

我已经尝试了该网站的许多建议,但没有任何效果,或者我没有很好地应用它们。我是 Python 和 Django 的新手,所以我会感谢所有帮助。

【问题讨论】:

    标签: python django django-urls


    【解决方案1】:

    出于某种原因,您以/store/ {% url 'details' album_id=album.id %} 的方式编写了您的网址。 url 模板标签将为您提供来自您网站域的相对 url,因此您 不必 必须为您的 url 添加前缀。你也写src="{{ album.picture }}"这里我假设picture是一个图像字段?如果是这样,您应该改写src="{{ album.picture.url }}"。因此,将您的模板更改为:

    {% 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 %}
    

    【讨论】:

    • 哦,谢谢。我没看到。现在它工作正常
    猜你喜欢
    • 2020-04-04
    • 1970-01-01
    • 1970-01-01
    • 2020-02-23
    • 2021-03-17
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    • 2015-10-05
    相关资源
    最近更新 更多