ValueError when getting objects by id

后端 未结 4 1599
无人及你
无人及你 2021-01-23 10:19

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

相关标签:
4条回答
  • 2021-01-23 10:46

    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.

    0 讨论(0)
  • 2021-01-23 10:53

    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.

    0 讨论(0)
  • 2021-01-23 10:57

    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.

    0 讨论(0)
  • 2021-01-23 11:08

    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 ''.

    0 讨论(0)
提交回复
热议问题