我正在尝试从特定客户端删除报告,因此目前在我的url.py
我传递客户端ID和报告ID,希望从客户端X删除报告Y.我本可以使用def ReportScheduleDeleteView(request):
,但希望使用基于类的DeleteView。
我查看了this example
,但无法与我的代码混合。
所以这是我的代码。
urls.py
url(r'^jsclient/(?P<pk>\d+)/report/(?P<r_pk>\d+)/delete/$', ReportScheduleDeleteView.as_view(), name="report-delete"),
models.py -
class JSClient(models.Model):
name = models.CharField(max_length=255, unique=True)
clientAccount = models.CharField(max_length=255)
....
class ReportSchedule(models.Model):
client = models.ForeignKey(JSClient)
schedRepName = models.CharField(max_length=255)
reportType = models.CharField(max_length=255, choices=REPORT_TYPE)
....
views.py:
class ReportScheduleDeleteView(DeleteView):
model = ReportSchedule
template_name = "report/report_confirm_delete.html"
success_url = lazy(reverse, str)('jsclient-list')
我确信必须有一种方法可以使用基于类的DeleteView执行此操作,对此有任何帮助。
答案 0 :(得分:5)
感谢EsseTi
和CCBV site
的提示,我设法解决了我的问题的解决方案。这可能是显而易见的
class ReportScheduleDeleteView(DeleteView):
model = ReportSchedule
template_name = "report/report_confirm_delete.html"
success_url = lazy(reverse, str)('jsclient-list')
# Get the parameters passed in the url so they can be used in the
# "report/report_confirm_delete.html"
**UPDATE:**
def get_object(self, queryset=None):
if queryset is None:
queryset = self.get_queryset()
client = self.kwargs['pk']
report = self.kwargs['rpk']
queryset = ReportSchedule.objects.filter(client_id=client, id=report)
if not queryset:
raise Http404
context = {'client_id':client, 'report_id':report}
return context
# Override the delete function to delete report Y from client X
# Finally redirect back to the client X page with the list of reports
def delete(self, request, *args, **kwargs):
client = self.kwargs['pk']
report = self.kwargs['rpk']
clientReport = ReportSchedule.objects.filter(client_id=client, id=report)
clientReport.delete()
return HttpResponseRedirect(reverse('report-list', kwargs={'pk': client}))
希望它有所帮助。
答案 1 :(得分:1)
它类似于Example of Django Class-Based DeleteView
重新定义def get_object(self, queryset=None)
并进行内部检查。
使用kwargs你应该能够从url获取参数。