Sama
Sama

Reputation: 55

Django, update value with Queryset

Im trying to update 1 value with a button on the frontend. But this is not working.

First some code snippets.

models.py

    DRAFT = "D"
    PUBLISHED = "P"
    CLOSED = "C"
    STATUS = (
        (DRAFT, _("Draft")),
        (PUBLISHED, _("Published")),
        (CLOSED, _("Closed")),
    )

    class Item(models.Model):
        user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, related_name="itemauthor", on_delete=models.SET_NULL)
        slug = models.SlugField(max_length=80, null=True, blank=True)
        status = models.CharField(max_length=1, choices=STATUS, default=DRAFT)
        ...

views.py

class DeleteItemView(ListView, UpdateView):
    def get_queryset(self):
        Item.objects.filter(pk=self).update(status='C')

urls.py

urlpatterns = [
    ...
    url(r'^delete/(?P<pk>\d+)/$', DeleteItemView.as_view(), name='delete_article'),
    ...
]

.html

a class="btn btn-success" href="{% url 'offers:delete_article' object.pk %}" title="{% trans 'Delete Item' %}"><i class="fa fa-pencil" aria-hidden="true"></i> {% trans 'Delete Item' %}</a>

But this will not work, I jump from one error to the next. I get this error message from Django

int() argument must be a string, a bytes-like object or a number, not 'DeleteItemView'
Request Method: GET
Request URL:    http://127.0.0.1:8000/offers/delete/2/
Django Version: 2.2.2
Exception Type: TypeError
Exception Value:    
int() argument must be a string, a bytes-like object or a number, not 'DeleteItemView'
Exception Location: /home/PycharmProjects/base_camp/venv/lib/python3.7/site-packages/django/db/models/fields/__init__.py in get_prep_value, line 966
Python Executable:  /home/PycharmProjects/base_camp/venv/bin/python
Python Version: 3.7.3

where do I make the mistake here?

Upvotes: 1

Views: 111

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477607

The pk can not be self, it should be self.kwargs['pk']. That being said, it probably makes more sense to use a DeleteView here, and patch the delete function, like:

from django.views.generic import DeleteView

class DeleteItemView(DeleteView):

    model = Item

    def delete(self, request, *args, **kwargs):
        self.object = self.get_object()
        success_url = self.get_success_url()
        self.object.status = 'C'
        self.object.save()
        return HttpResponseRedirect(success_url)

Note that you will need to make a POST or DELETE request in order to delete the object, so you can make a mini form for example with:

<form action={% url 'offers:delete_article' object.pk %}" method="post">
    <button type="submit" class="btn btn-success" href=" title="{% trans 'Delete Item' %}"><i class="fa fa-pencil" aria-hidden="true"></i> {% trans 'Delete Item' %}</button>
</form>

Upvotes: 1

Related Questions