Python Django slug url错误

时间:2018-06-19 07:10:55

标签: python django

我正在写一个练习python django网站。我正在尝试将我的contact.html中的链接,slugs连接到单独的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文件都是联系人/联系人/模板)

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

1 个答案:

答案 0 :(得分:1)

您的网址标记的左括号后面有空格,因此无法解析。删除空格。

 "{ % url 'detail' slug = contact.slug %}"
#  ^ here