Django详细网址

时间:2018-11-07 14:03:42

标签: python django view

我正在尝试为博客应用程序的每个条目创建单独的URL。但是每次我尝试去例如:localhost:8000 / blog / 3时,它都会向我发送常规localhost:8000 / blog的响应

我试图用Google搜索它,而且...我不知道自己在做什么错。

我的标准url.py:

from django.conf.urls import url, include
from django.contrib import admin
...
import blog.views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url('home/', jobs.views.home, name='home'),
    url(r'^blog/', include('blog.urls')),
    ]

urls.py(在“博客应用”文件夹中):

from django.conf.urls import url, include
from . import views

urlpatterns = [
    url('<int:blog_id>/', views.detail, name="detail"),
    url('', views.allblogs, name="allblogs"),
]

views.py:

from django.shortcuts import render, get_object_or_404
from .models import Article


def allblogs(request):
    #Mega object from database
    blog = Article.objects
    return render(request, "blog/allblogs.html", {'blog':blog})


def detail(request, blog_id):
    blog = get_object_or_404(Article, pk=blog_id)
    return render(request, "blog/detail.html", {'blog':blog})

在models.py中,我不知道为什么选择“ Article”而不是“ Blog”,但我认为这并不重要...

任何想法...?

2 个答案:

答案 0 :(得分:0)

请确保您使用的是正确的符号,具体取决于您的Django版本。

Django 1.11及更低版本:

from django.conf.urls import url
...
url(r'^$', views.allblogs, name='allblogs')

Django 2.0:

from django.urls import path
....
path('', views.index, name='allblogs'),

答案 1 :(得分:0)

我建议使用这种方法: 模板:

<a href="{% url 'blog:detail_blog' blog.pk %}" type="button" class="btn btn-primary btn-block btn-xs" >
<i class="fa fa-eye"> Edit</i>
</a>

在这种情况下,我说的是访问应用博客的模板和url detail_blog并发送pk(id)以获得或显示详细信息。

您的网址主体:

urlpatterns = [
.......
.......
url(r'blog/', include('blog.urls', namespace='blog')),
]

您来自应用博客的urls.py:

from blog.views import DetailBlog
urlpatterns = [
....
....
url(r'^detail_blog/(?P<pk>\d+)', DetailBlog.as_view(), name='detail_blog')
]

您的views.py:

class DetailBlog(DetailView):
    model = Blog
    template_name = 'detail_blog.html'
    slug_field = 'title'

Es seria todo,espero te sirva,准市长推荐人链接:

Vistas Genericas Django