我是django的新手,想要将id / pk转换为slug ,我想让 url变得友好或易于理解
想要将网址http://127.0.0.1:8000/1/
设为http://127.0.0.1:8000/hello/
Model.py
class Post(models.Model):
title=models.CharField(max_length=200)
description=models.TextField(max_length=10000)
pub_date=models.DateTimeField(auto_now_add=True)
comments=models.CharField(max_length=200, blank=True)
slug = models.SlugField(max_length=40, unique=True)
def __unicode__(self):
return self.title
def description_as_list(self):
return self.description.split('\n')
admin.py
class PostAdmin(admin.ModelAdmin):
list_display=['title','description']
prepopulated_fields = {'slug': ('title',)}
class Meta:
model = Post
admin.site.register(Post,PostAdmin)
urls.py
urlpatterns = [
url(r'^$', views.PostListView.as_view(),name='home'),
url(r'^(?P<slug>[\w-]+)/$', views.detail, name='detail'),
]
views.py
class PostListView(ListView):
model = Post
template_name = 'blog_post.html'
queryset = Post.objects.order_by('-pub_date')
paginate_by = 2
def detail(request, id):
posts = Post.objects.get(id=id)
return render(request, "blog_detail.html", {'posts': posts,})
模板
{% for threads in object_list %}
<p class="blog-post-title"><a href="{% url 'detail' slug=threads.id %}">{{ threads.title }}</a></p>
<hr />
{% endfor %}
任何帮助都可以使url可读。谢谢davance
答案 0 :(得分:1)
要实现您的目标,您需要将slug参数传递给views.py的详细功能,如下所示:
def detail(request, slug):
posts = Post.objects.get(slug=slug)
return render(request, "blog_detail.html", {'posts': posts,})
此外,您的blog_post.html模板应该接受网址中的slug:
{% for threads in object_list %}
<p class="blog-post-title"><a href="{% url 'detail' slug=threads.slug %}">{{ threads.title }}</a></p>
<hr />
{% endfor %}
当然,您需要为详细信息视图提供blog_detail模板。