【发布时间】:2018-11-28 01:41:30
【问题描述】:
我正在写一个练习 python django 的网站。我正在尝试将我的contact.html 中的链接、slug 连接到单独的html 页面。为这些对象手动输入 URL 会正确输出站点。但是,contact.html 中的链接不喜欢这些页面。
{% extends "base.html" %}
<!DOCTYPE html>
{% block content %}
<body>
<h1>Contact page</h1>
<div class = "contact">
{% for contact in contact %}
<h2><a href="{ % url 'detail' slug = contact.slug %}">{{contact.title}}</a></h2>
{% endfor %}
</div>
</body>
{% endblock %}
contact_detail.html(contact.html 中的页面href 应该喜欢这个html;两个html 文件都在contact/contact/templates)
{% extends "base.html" %}
<!DOCTYPE html>
{% block content %}
<body>
<div class = "contact">
<p>{{contact.title}}</p>
<p>{{contact.body}}</p>
</div>
</body>
{% endblock %}
views.py
from django.shortcuts import render
from .models import Contact
from django.http import HttpResponse
def contact(request):
contact = Contact.objects.all()
return render(request, 'contact/templates/contact.html', {'contact': contact})
def contact_details(request, slug):
contacts = Contact.objects.get(slug=slug)
return render(request, 'contact/templates/contact_detail.html', {'contact': contacts})
urls.py
from django.urls import re_path
from . import views
from django.conf.urls import url
from django.conf.urls.static import static
urlpatterns = [
url('^$', views.contact, name="list"),
url(r'^(?P<slug>[\w-]+)/$', views.contact_details, name = "detail"),
]
models.py
from django.db import models
class Contact(models.Model):
title = models.CharField(max_length=500)
slug = models.SlugField()
body = models.TextField()
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def snippet(self):
return self.body[:50]
admin.py
from django.contrib import admin
from .models import Contact
# Register your models here.
admin.site.register(Contact)
错误
Using the URLconf defined in katiesite.urls, Django tried these URL patterns, in this order:
admin/
^contact/ ^$ [name='list']
^contact/ ^(?P<slug>[\w-]+)/$ [name='detail']
^$
The current path, contact/{ % url 'detail' slug = contact1.slug %}, didn't match any of these.
【问题讨论】: