django CreateView 要求 pk

django CreateView demands pk

这是我的 CreateView:

class LampCreateView(CreateView):
    model = Lamp
    template_name = 'shotmaker/test_cam.html'
    success_url = '/shotmaker/'

及其 url:

url(r'^camera/create/$', views.LampCreateView.as_view(), name='lamp_create'),

当我尝试打开 URL 时,我得到了这个:

ValueError at /shotmaker/camera/create/
invalid literal for int() with base 10: 'create'

当我将 pk 传递给 url 时:

url(r'^camera/create/(?P<pk>[-\w]+)$', views.LampCreateView.as_view(), name='lamp_create'),

视图打开正常。

如果这是一个 CreateView,为什么还需要 pk? pk 不应该存在!

如果您查看完整的回溯,您应该能够看到引发异常的不是 LampCreateView

听起来您在 lamp_create 上方还有另一个 url 模式,它首先匹配 /shotmaker/camera/create/。例如:

url(r'^camera/(?P<pk>[-\w]+)/$', views.OtherView.as_view(), name='other_view')
url(r'^camera/create/(?P<pk>[-\w]+)$', views.LampCreateView.as_view(), name='lamp_create'),

解决问题,将other_viewurl移到lamp_createurl下方。