我正在尝试在Django项目中设置Slug URL。我一直收到404错误,找不到我错过的内容。我之前已经做了好几次,但由于某种原因,我必须遗漏一些东西。
models.py
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
# Create your models here.
class Pages(models.Model):
title = models.CharField(max_length=250, default="Add Title Here")
content = models.TextField(default="Add Content Here")
slug = models.SlugField(unique=True)
seo_title = models.CharField(max_length=250, default="Add Title Here")
seo_description = models.CharField(max_length=160, default="Add Seo Description")
active = models.BooleanField(default=False)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False, null=True)
updated = models.DateTimeField(auto_now_add=False, auto_now=True, null=True)
def __unicode__(self):
return self.title
class Meta:
unique_together = ('slug', 'title')
def get_absolute_url(self):
return reverse("single_page", kwargs={"slug": self.slug})
views.py
from django.shortcuts import render, get_object_or_404, Http404
# Create your views here.
from .models import Pages
def Single(request, slug):
try:
page = get_object_or_404(Pages, slug=slug)
context = {'page': page}
template = 'pages/page_detail.html'
return render(request, template, context)
except:
raise Http404
urls.py
from django.conf.urls import url, patterns
from . import views
urlpatterns = [
url(r'^(?P<slug>[\w-]+)/$', views.Single, name='single_page'),
]
答案 0 :(得分:0)
谢谢你们的帮助。我在@vastlysuperiorma
的帮助下找到了这个问题Views.py
def single(request, slug):
try:
page = get_object_or_404(Pages, slug=slug)
context = {'page': page}
template = 'pages/page_detail.html'
return render(request, template, context)
except Pages.DoesNotExist:
raise Http404