djangodjango-modelsdjango-file-upload

How can my users delete a file that they uploaded using latest Django version?


I'm not getting an error message---but when the Delete button is pressed in my template, nothing happens. Does anyone see what's missing in my code below?

settings.py

MEDIA_URL = '/home/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 
             'home/')

models.py

class Roll(models.Model):
    csv = models.FileField(default="", upload_to='home/')

    def delete(self, *args, **kwargs):
        self.csv.delete()
        super().delete(*args, **kwargs)

views.py

class DeleteRollView(LoginRequiredMixin, DeleteView):
    model = Roll
    form_class = RollForm
    template_name = 'users/delete_roll.html'

    @staticmethod
    def delete_roll(self, request, pk):
        if request.method == 'POST':
            roll = Roll.objects.get(pk=pk)
            roll.delete()
        return redirect('users:list_roll')

delete_roll.html

<input type="submit" value="Delete"/>

Solution

  • Revised CBV method, per Som-1's suggestion :

    def post(self, request, *args, **kwargs):
        if request.method == 'POST':
            roll =   
            Roll.objects.get(id=self.kwargs['pk'])
            roll.delete()
        return redirect('users:list_roll')