如何获取传递给django CBV的URL参数?

时间:2013-07-01 22:15:04

标签: django django-urls django-class-based-views

我有一个urls.py文件设置如下

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

urlpatterns = patterns('',
    url(r'^$', BlogListView.as_view()),
    url(r'(?P<blog_id>)\d{1,}/$', BlogDetailView.as_view())
)

带有关联视图

class BlogDetailView(View):
    def get(self, request, blog_id, *args, **kwargs):
        post = Blog.objects.get(post_id=blog_id).to_detail_json
        return HttpResponse(json.dumps(post), mimetype='application/json')

访问127.0.0.1:8000/blog/1 /

时出错
ValueError at /blog/4/
invalid literal for int() with base 10: ''

但如果我改变

post = Blog.objects.get(post_id=blog_id).to_detail_json

post = Blog.objects.get(post_id=1).to_detail_json

然后我得到了正确的答案。

如果需要,这是我的模型

from mongoengine import *
from collections import OrderedDict

import datetime
import json

class Blog(Document):
    post_id = IntField(unique=True)
    title = StringField(max_length=144, required=True)
    date_created = DateTimeField(default=datetime.datetime.now)
    body = StringField(required=True)

    def __init__(self, *args, **kwargs):
        self.schema = {
        "title": self.title,
        "date": str(self.date_created),
        "id": self.post_id,
        "body": self.body
    }
            super(Blog, self).__init__(*args, **kwargs)
    @property
    def to_detail_json(self):
        fields = ["id","title", "date", "body"]
        return {key:self.schema[key] for key in fields}

    @property
    def to_list_json(self):
        fields = ["title", "date"]
        return {key:self.schema[key] for key in fields}

更新

我更改了BlogDetailView以返回

return HttpResponse(json.dumps(self.kwargs),mimetype='application/json')

它给了我

{
    blog_id: ""
}

这让我相信它与我的urls.py文件有关,但我没有看到错误。

2 个答案:

答案 0 :(得分:3)

post = Blog.objects.get(post_id=self.kwargs['blog_id']).to_detail_json

答案 1 :(得分:0)

事实证明

url(r'(?P<blog_id>)\d{1,}/$', BlogDetailView.as_view())

应该是

url(r'(?P<blog_id>\d{1,})/$', BlogDetailView.as_view())