通过ID获取对象时的ValueError [英] ValueError when getting objects by 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))
Urlconf
url(r'^ cribme /(?P< meekme_id>)\d + / $','meebapp.views.cribdetail',name ='cribdetail'),
在模板中:
< a href ={%url cribdetail post.id%}> {{result.object.title}}< / a>
当我点击我的模板中的上述链接时,我得到以下错误:
/ cribme / 0 /
中的ValueError与基数为10的int()无效文字:''
请求方法:GET
请求URL:http://127.0.0.1:8000/cribme/0/
Django版本:1.4
异常类型:ValueError
异常值:
带有基数10的int()的无效字面值:''
异常位置:C:\Python27\lib\site- packages\\ \\ django\db\models\fields\__init __。py在get_prep_value中,第537行
Python可执行文件:C:\Python27\python.exe
Python版本:2.7.3
与此战斗了一段时间。如何摆脱这个错误?
向我看,你的urlconf是责怪的,应该是: p>
url(r'^ cribme /(?P< meekme_id> \d +)/ $','meebapp.views.cribdetail' ,name ='cribdetail'),
不是:
url(r'^ cribme /(?P< meekme_id>)\d + / $','meebapp.views.cribdetail',name ='cribdetail'),
?P< meekme_id>
表示匹配的字符串括号之间的这个名称。()不匹配,这就是为什么你的应用程序在尝试查找id ''
的项目时发出错误。
如果括号中包含 \d +
,则匹配一个自然数,这应该适用。
I'm trying to get data by id in my django app. The problem is that I don't know the kind of id the user will click on. I input the below codes in views.
Views
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))
Urlconf
url(r'^cribme/(?P<meekme_id>)\d+/$', 'meebapp.views.cribdetail', name='cribdetail'),
In template:
<a href="{% url cribdetail post.id %}">{{ result.object.title }}</a>
When I click on the above link in my template, I'm getting the below error:
ValueError at /cribme/0/
invalid literal for int() with base 10: ''
Request Method: GET
Request URL: http://127.0.0.1:8000/cribme/0/
Django Version: 1.4
Exception Type: ValueError
Exception Value:
invalid literal for int() with base 10: ''
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
Been fighting with this for a while now. How can I get rid of that error?
looks to me that your urlconf is to blame, it should be:
url(r'^cribme/(?P<meekme_id>\d+)/$', 'meebapp.views.cribdetail', name='cribdetail'),
not:
url(r'^cribme/(?P<meekme_id>)\d+/$', 'meebapp.views.cribdetail', name='cribdetail'),
?P<meekme_id>
means "give the matched string between parentheses this name. () matches nothing, which is why your app give an error when trying to look up the item with id ''
.
When the parentheses enclose the \d+
, you match a natural number, which should work.
这篇关于通过ID获取对象时的ValueError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!