2012-06-29 101 views
1

我想通过我的django应用程序中的id获取数据。问题是我不知道用户点击的id的种类。我尝试添加在我的意见下面的代码,但我得到这个错误:在Django中通过id获取对象

ValueError at /findme/ 

invalid literal for int() with base 10: 'id' 

Request Method: GET 
Request URL: http://127.0.0.1:8000/findme/ 
Django Version: 1.4 
Exception Type: ValueError 
Exception Value: invalid literal for int() with base 10: 'id' 

Exception Location: C:\Python27\lib\site-packages\django\db\models\fields\__init__.py in get_prep_value, line 537 
Python Executable:  C:\Python27\python.exe 
    Python Version: 2.7.3 

查看

from meebapp.models import Meekme 

def cribdetail(request): 
    post=Meekme.objects.get(id='id') 
    return render_to_response('postdetail.html',{'post':post, 'Meekme':Meekme},context_instance=RequestContext(request)) 

我我缺少的是什么?

回答

4

的问题是,'id'是一个字符串,你需要在这里的整数关口:

post=Meekme.objects.get(id='id') 

应该最有可能是这样的:

def cribdetail(request, meekme_id): 
    post=Meekme.objects.get(id=meekme_id) 
    return render_to_response('postdetail.html',{'post':post, 'Meekme':Meekme},context_instance=RequestContext(request)) 

其中meekme_id是一个整数网址的一部分。你的URL配置应包含以下内容:

url(r'^example/(?P<meekme_id>\d+)/$', 'example.views.cribdetail'), 

当您访问example/3/,这意味着Django会调用视图cribdetail与分配给meekme_id值3。有关更多详细信息,请参阅Django URL documentation

+0

按照您的说明操作后,我收到此错误:NoReverseMatch at/search/ 未找到参数'()'和关键字参数'{}'的'meebapp.views.cribdetail'反向。 Urlconf:url(r'^ cribme /(?P \ d +)/ $','meebapp.views.cribdetail'),在模型中:def get_absolute_url(self): return('meebapp.views.cribdetail', ),[str(self.id)]]在模板中:我错过了什么? – picomon

+0

@picomon:在这种情况下,你会给Django的反向函数提供不正确的参数。您需要确保反转URL的名称和值是正确的,并且确实存在具有该名称和这些参数的URL。 –

+0

我可以在参数中单独输入ID吗?顺便说一句:检查我的编辑在上面的评论。 – picomon

1

错误消息是说'id'是整数 但您传递字符串。

+0

您必须将id作为整数传递。西梅昂只是举例。 – Nilesh

相关问题