我有一个 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 文件有关,但我没有看到错误。