我已经按照我给出的建议,但仍然没有在网址中显示slu ..当我尝试运行它时,我收到以下错误:
Page not found (404)
Request Method: GET
Request URL: http://localhost:8080/blog/1/
Raised by: blog.views.detail
我被告知是否更改了我的观点中的值
detail(request, blog_id):
page = "blog/detail.html"
title = "Detail"
context = {
"post": get_object_or_404(Post, pk=blog_id),
}
到这个
detail(request, slug):
page = "blog/detail.html"
title = "Detail"
context = {
"post": get_object_or_404(Post, slug=slug),
}
并将我的网址更改为
url(r'^(?P<slug>[\w-]+)/$', views.detail, name='detail'),
它会起作用,但事实并非如此。下面是我的代码,现在在下面。
我在models.py中的帖子模型看起来像这样
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
slug = models.SlugField()
img = models.CharField(max_length=100)
created = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
author = models.ForeignKey(Author)
categories = models.ManyToManyField(Category)
tags = models.ManyToManyField(Tag)
def __str__(self):
return self.title
class Meta:
ordering = ["-created"]
我的views.py看起来像这样
from django.shortcuts import render, get_object_or_404
from .models import Post
def detail(request, slug):
page = "blog/detail.html"
title = "Detail"
context = {
"post": get_object_or_404(Post, slug=slug),
"title": title,
}
return render(request, page, context)
我的博客/ urls.py看起来像这样
from django.conf.urls import url
app_name = 'blog'
from . import views
urlpatterns = [
# ex: /blog/
url(r'^$', views.index, name='index'),
# ex: /blog/5/
url(r'^(?P<slug>[\w-]+)/$', views.detail, name='detail'),
# ex: /blog/contact
url(r'^contact$', views.contact, name='contact'),
]
我的网站/ urls.py看起来像这样
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^blog/', include('blog.urls')),
url(r'^admin/', admin.site.urls),
url(r'^$', 'blog.views.land'),
]
我的admin.py看起来像这样
from django.contrib import admin
from .models import Post, Author, Category, Tag
class PostAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)}
search_fields = ['title', 'body']
list_display = ['title', 'body', 'created']
list_filter = ['created']
admin.site.register(Post, PostAdmin)
邀请并欢迎任何和所有帮助指导建议或教程。感谢
答案 0 :(得分:1)
正如我在帖子中看到的那样:您尝试了网址http://localhost:8080/blog/1/
,但这是旧网址,您需要新的网址,例如http://localhost:8080/blog/slug/
...
您还应将get_object_or_404(Post, slug)
更改为get_object_or_404(Post, slug=slug)
。
有关详细信息,请参阅https://docs.djangoproject.com/en/1.9/_modules/django/shortcuts/#get_object_or_404,获取预期关键字参数,而不是位置:https://docs.djangoproject.com/en/1.9/ref/models/querysets/#django.db.models.query.QuerySet.get
答案 1 :(得分:0)
检查你是否真的有一个slug 1
的帖子。在我看来,您使用/blog/1
来获取pk
的帖子,所以现在它不会起作用,因为帖子1
根本不存在
答案 2 :(得分:0)
正则表达式是这个
(?P<slug>[\w-]+)
什么时候应该是这个
(?P<slug>[\w\-]+)
感谢所有试图提供帮助的人。我很高兴我没有放弃。这让我开启了新的一年!