我正在尝试在django应用程序中通过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))
Urlconf
url(r'^cribme/(?P<meekme_id>)\d+/$', 'meebapp.views.cribdetail', name='cribdetail'),
在模板中:
<a href="{% url cribdetail post.id %}">{{ result.object.title }}</a>
当我单击模板中的以上链接时,出现以下错误:
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
已经为此战斗了一段时间。如何摆脱该错误?
最佳答案
在我看来,您的urlconf应该受到指责,应该是:
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+
括起来时,您将匹配一个自然数,该数应该起作用。