Last active
January 7, 2019 09:25
-
-
Save mpapierski/e18156e22579b94caa5466416e1275ca to your computer and use it in GitHub Desktop.
Custom delete in Django
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class FooManager(models.Manager): | |
"""A manager for foos with custom filter. | |
Adds a clause to default query to ignore removed entries. | |
""" | |
def get_queryset(self): | |
"""Filter out all removed entries by default.""" | |
return super().get_queryset().filter(removed_at__isnull=True) | |
class Foo(models.Model): | |
"""Foo holds information about different foos. | |
""" | |
# ... | |
objects = FooManager() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class FooDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): | |
"""List all foos.""" | |
model = Foo | |
success_url = reverse_lazy('foo_list') | |
def test_func(self): | |
"""Check if this foo belongs to the same | |
customer as user.""" | |
return self.request.user.customer == self.get_object().customer | |
def delete(self, request, *args, **kwargs): | |
self.object = self.get_object() | |
success_url = self.get_success_url() | |
self.object.removed_at = timezone.now() | |
self.object.save() | |
return HttpResponseRedirect(success_url) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment