Django 1.7匹配查询不存在

时间:2016-02-02 17:58:08

标签: django django-class-based-views django-1.7

当我尝试创建一个基于类的视图来修改我的模型Destino时出现以下错误。 如果可能的话,我会在urls.py

中不使用slug或pk

错误:

Destino matching query does not exist.
Request Method: GET
Request URL:    http://localhost:8002/modificarVC/modificar.html
Django Version: 1.7
Exception Type: DoesNotExist
Exception Value:    
Destino matching query does not exist.
Exception Location: /usr/local/lib/python2.7/dist-packages/Django-1.7-      py2.7.egg/django/db/models/query.py in get, line 357
Python Executable:  /usr/bin/python
Python Version: 2.7.6
Python Path:    
['/home/juanma/Escritorio/exPWfebrero/Django/AgenciaViajes',
 '/usr/local/lib/python2.7/dist-packages/Django-1.7-py2.7.egg',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-x86_64-linux-gnu',
 '/usr/lib/python2.7/lib-tk',
 '/usr/lib/python2.7/lib-old',
 '/usr/lib/python2.7/lib-dynload',
  '/usr/local/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages/PILcompat',
 '/usr/lib/python2.7/dist-packages/gtk-2.0',
 '/usr/lib/python2.7/dist-packages/ubuntu-sso-client',
 '/usr/lib/python2.7/dist-packages/wx-2.8-gtk2-unicode']

URLS:

url(r'^modificarVC/modificar.html', modificarVC.as_view(), name='modificarDestino'),

视图:

class modificarVC(UpdateView):
    model = Destino
    template_name = "modificarVC/modificar.html"
    success_url = '/'

    def get_object(self):
        return Destino.objects.get(pk=self.request.GET.get('pk'))

2 个答案:

答案 0 :(得分:0)

正如一些评论所述,你做了一些与基于类的观点相悖的事情。关于你正在使用的UpdateView,它期望传入一个pk。

# urls.py
url(r'^modificarVC/modificar/(?P<pk>\d+)/$', modificarVC.as_view(), name='modificarDestino')

当您点击/modificarVC/modificar/5/等网址时,UpdateView会自动设置对象,方法是选择模型Destino中ID为5的对象。

# views.py
class modificarVC(UpdateView):
    model = Destino
    template_name = "modificarVC/modificar.html"
    success_url = '/'

答案 1 :(得分:0)

您的错误消息提示有问题 - 您的请求网址未包含'pk'请求参数(请参阅“请求网址”)

Destino matching query does not exist.
Request Method: GET
Request URL:    http://localhost:8002/modificarVC/modificar.html

再次运行您的请求,但将pk参数作为查询参数添加到结尾:http://localhost:8002/modificarVC/modificar.html?pk=42