2016-02-27 77 views
2

我想通過它的pk字段訪問我的模型,當它是uuid表示形式時。我得到的年齡錯誤未找到404 on this addresshttp://localhost:8002/box/6d99a390-5a8a-41e6-8fbf-84a2bb7a8e0f` 我有這個配置如何通過Django中的uuid'檢索對象

def get_box(request, pk): 
    """ 
    Retrieve the object 
    """ 
    box = get_object_or_404(Box, pk=pk) 
    return render(
      request, 
      'boxes/box.html', 
      {'box':box} 
      ) 

和我的models.py

@python_2_unicode_compatible 
class Box(models.Model): 
    """ 
    Box model 
    """ 
    def __str__(self): 
     return self.title 
    id = models.UUIDField(primary_key=True, 
           default=uuid.uuid4, editable=False)  
    title = models.CharField(max_length=40, blank=True, null=True) 

和我的urls.py

... 
url(r'^box/(?P<pk>[0-9A-Za-z]+)/$', views.get_box, name='box'), 
... 
+1

請告訴我的錯誤?沒有反向匹配? – Sayse

+0

@Sayse否我有這個錯誤當前的URL,框/ 6d99a390-5a8a-41e6-8fbf-84a2bb7a8e0f,沒有匹配任何這些。 –

回答

4

問題不在於查詢,而在於URL。您的正則表達式只能匹配字母數字字符,但uuid也包含破折號;你應該包括那些模式:

r'^box/(?P<pk>[0-9A-Fa-f-]+)/$' 

(還要注意的是字符只能是A到F,而不是a到z)。

相關問題