调用模板中的“更新”和“删除”视图时,出现找不到页面(404)的情况。
我的模型使多个Staff可以具有多个Availability条目。因此,我创建了一个视图以列出每个员工的可用性条目,并且我认为使用同时使用员工的pk和可用性条目的pk的URL模式来删除或更新员工的特定可用性条目是有意义的。
示例:要编辑2号员工的可用性条目4: http://127.0.0.1:8000/staff/2/availability/4/edit
任何提示我为什么会收到此错误?
我做了一些研究,我想知道是否必须重写AvailabilityUpdateView和AvailabilityDeleteView中的get_object方法吗?
urls.py
path('staff/availability/new/', views.AvailabilityCreateView.as_view(), name='availability_new'),
path('staff/<int:pk>/availability/', views.AvailabilityListView.as_view(), name='availability_list'),
path('staff/<int:pk>/availability/<int:pk_alt>/edit/', views.AvailabilityUpdateView.as_view(), name='availability_edit'),
path('staff/<int:pk>/availability/<int:pk_alt>/delete/', views.AvailabilityDeleteView.as_view(), name='availability_delete'),
模板
<a href="{% url 'availability_edit' pk_alt=availability.pk pk=availability.staff.pk %}">Edit</a> |
<a href="{% url 'availability_delete' pk_alt=availability.pk pk=availability.staff.pk %}">Delete</a>
观看次数
class AvailabilityUpdateView(UpdateView):
template_name = 'crm/availability_form.html'
form_class = AvailabilityForm
model = Availability
class AvailabilityDeleteView(UpdateView):
template_name = 'crm/availability_confirm_delete.html'
model = Availability
success_url = reverse_lazy('staff_list')
答案 0 :(得分:2)
这里的问题是,默认情况下,django在您的URL中寻找一个pk
kwarg来获取对象,但是您将其pk_alt
作为可用性的pk发送;只需在您的视图中更改pk_url_kwarg
:
class AvailabilityUpdateView(UpdateView):
template_name = 'crm/availability_form.html'
form_class = AvailabilityForm
model = Availability
pk_url_kwarg = 'pk_alt'
class AvailabilityDeleteView(DeleteView): # <-- shouldn't it be DeleteView?
template_name = 'crm/availability_confirm_delete.html'
model = Availability
success_url = reverse_lazy('staff_list')
pk_url_kwarg = 'pk_alt'
尽管在您的情况下,您似乎想防止人员编辑其他人员的可用性,所以最好重写get_object
方法控制:
class AvailabilityUpdateView(UpdateView):
template_name = 'crm/availability_form.html'
form_class = AvailabilityForm
model = Availability
def get_object(self):
return Availability.objects.get_object_or_404(pk=self.request.GET.get('pk_alt'), staff_id=self.request.GET.get('pk')) # or request.POST
class AvailabilityDeleteView(DeleteView): # <-- shouldn't it be DeleteView?
template_name = 'crm/availability_confirm_delete.html'
model = Availability
success_url = reverse_lazy('staff_list')
def get_object(self):
return Availability.objects.get_object_or_404(pk=self.request.GET.get('pk_alt'), staff_id=self.request.GET.get('pk')) # or request.POST