2

I am trying to delete a report from a particular client, so currently in my url.py i am passing the client id and the report id, hoping to delete report Y from client X. I could have done this using def ReportScheduleDeleteView(request): , but was hoping to use the Class-Based DeleteView.

I had a look at this example but wasn't able to blend with my code.

So here is my code.

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')

I am sure there must be a way of doing this using the Class-Based DeleteView, any help on this is appreciated.

4

2 回答 2

6

感谢来自的提示EsseTiCCBV 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}))

希望它对某人有所帮助。

于 2013-05-17T13:25:13.773 回答
1

这与基于 Django 类的 DeleteView 的示例类似

重新定义def get_object(self, queryset=None)并在内部进行检查。使用 kwargs 你应该能够从 url 获取参数。

于 2013-05-17T10:43:50.273 回答