Django URL Mapping / DetailView的问题

时间:2017-05-04 12:07:36

标签: regex django django-generic-views

我是Django的新手并且一直在制作示例项目。我一直在尝试使用Generic Detailview。似乎url重定向工作正常,但DetailView无法从url获取primarykey。

主要网址:

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^',include('personal.urls')),
]  

这是我的应用的urls.py代码:

urlpatterns = [
 url(r'(?P<pk>\d+)/$',views.detailView.as_view(),name="detail"),]

查看DetailView的文件:

from django.shortcuts import render
from django.views import generic
from .models import  Story


class detailView(generic.DetailView):
    model = Story
    template_name = 'personal/storydetail.html'

    def get_context_data(self, **kwargs):
        pk = kwargs.get('pk')  # this is the primary key from your URL
        print("PK:",pk)

模板代码:

{% block content %}
{{ Story.writer }}
<h6> on {{ Story.story_title }}</h6>
<div class = "container">
    {{ Story.collection }}
</div>
{% endblock %}

故事类代码:

class Story(models.Model):
     story_title = models.CharField(max_length=200) #Story title
     writer = models.CharField(max_length=200) #WriterName
     collection=models.CharField(max_length=200) #Collection/Book name

当我在视图上检查主键值时,它显示“NONE”。我找不到代码的问题。我的网址类似于:http://127.0.0.1:8000/personal/2/其中,personal是app的名称,2应该被视为id。

1 个答案:

答案 0 :(得分:1)

问题是您在kwargs方法中使用的是self.kwargs而不是get_context_data。它应该是这样的:

def get_context_data(self, **kwargs):
    # You need to call super() here, so that the context from the DetailView is included
    kwargs = super(detailView, self).get_context_data(**kwargs)

    pk = self.kwargs['pk']  # No need for get() here -- if you get a KeyError then you have a problem in your URL config that should be fixe  # this is the primary key from your URL

    # edit kwargs as necessary
    ...
    return kwargs

get_context_data方法中,kwargs是传递给方法以构成上下文的方法。它们与self.kwargs不同,后者来自网址模式。