ValueError when getting objects by id

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-02 09:01:28

问题


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?


回答1:


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.




回答2:


The regex in your urlconf needs a little tweak:

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

The value of the meekme_id parameter wasn't being captured, since the \d+ was outside the parentheses.




回答3:


You misplaced a closing parenthesis:

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

Note that the (?P<meekme_id> .. ) group construct should include the \d+ characters you are trying to match. In your incorrect regular expression you define a group that doesn't include any matched characters, thus always the empty string ''.




回答4:


In addition to the URL problem, you are not generating the right link in the first place - you refer to result.object.title but post.id in the template, which is why your URL contains 0 for the ID. I expect you mean result.id or result.object.id.



来源:https://stackoverflow.com/questions/11264655/valueerror-when-getting-objects-by-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!