【问题标题】:Python Django slug url errorPython Django slug url错误
【发布时间】: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.

【问题讨论】:

    标签: python django


    【解决方案1】:

    您的 URL 标记的左括号后有一个空格,因此它不会被解析。删除空格。

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

    【讨论】:

    • 我试过了,但它仍然返回错误。它声明(当前路径联系人/{ % url)。它似乎没有注册更改。我确保保存 url 甚至迁移服务器
    猜你喜欢
    • 2018-01-06
    • 1970-01-01
    • 2015-07-27
    • 2017-09-08
    • 2021-10-08
    • 2021-06-29
    • 2018-10-26
    • 2011-08-15
    • 2014-11-06
    相关资源
    最近更新 更多