无法在Django中使slug工作

时间:2018-04-04 11:18:57

标签: python django

我正在构建一个项目,其中我使用slug作为网址。但它似乎并没有起作用。我的正则表达式是对的我已经测试过了。我之前使用过id然后它工作正常但是如果我使用slug代替id它会产生错误。这是我的代码

models.py

from django.db import models
class Category(models.Model):
   name = models.CharField(max_length=100)
   slug = models.SlugField(unique=True)

   class Meta:
      verbose_name = 'Category'
      verbose_name_plural = 'Categories'

   def __str__(self):
      return self.name

class Country(models.Model):
   name = models.CharField(max_length=100)
   slug = models.SlugField(unique=True)

   class Meta:
      verbose_name = 'Country'
      verbose_name_plural = 'Countries'

   def __str__(self):
      return self.name

class News(models.Model):
   title = models.CharField(max_length=100)
   slug = models.SlugField(unique=True)
   category = models.ForeignKey(Category, on_delete=models.CASCADE)
   country = models.ForeignKey(Country, on_delete=models.CASCADE)
   description = models.TextField(max_length=1500)
   pub_date = models.DateTimeField()

   class Meta:
      verbose_name = 'News'
      verbose_name_plural = 'News'

   def __str__(self):
      return self.title

urls.py

from django.conf.urls import url
from . import views
urlpatterns = [
   url(r'^$', views.Home, name='index'),
   url(r'^[a-z0-9-]+$/detail', views.detail, name='detail')]

views.py

def detail(request, slug):
   nd = get_object_or_404(News, slug=slug)
   return render(request, template_name="app/detail.html", context={'nd':nd})

detail.html

{% extends "base.html" %}
{% block title %}Detail{% endblock %}
{% block content %}
<div class="home">
    {% for n in nd %}
        <h2>{{ n.title }}</h2>
        <h4>{{ n.category }}</h4>
        <h4>{{ n.pub_date }}</h4>
        <p>{{ n.description }}</p>
{% endfor %}
</div>
{% endblock %}

2 个答案:

答案 0 :(得分:0)

让它改变工作

url(r'^[a-z0-9-]+$/detail', views.detail, name='detail')

url(r'^(?P<slug>[-\w]+)/detail/$', views.detail, name='detail')

答案 1 :(得分:0)

您没有在网址格式中捕获参数,因此不会将其发送到视图。

rootNavigator