Django - get_object_or_404() takes at least 1 argument (0 given)

1.2k views Asked by At

I'm trying to create a page where I can delete an article using class based views. There is one problem, I am getting an error which says :

id() takes exactly one argument (0 given)

here is the code :

views.py

class DeleteView(View):
    def post(self, request, *args, **kwargs):
        article = get_object_or_404(Article, id=id)
        article.delete()
        return HttpResponseRedirect('/')

    def get(self, request, *args, **kwargs):
        article = Article.objects.get(id=kwargs['id'])
        context = {"article": article}
        return render_to_response("delete.html", context, context_instance=RequestContext(request))

template.html

<div class="col-xs-12 col-sm-8 col-md-8 col-lg-8">
<form action="{% url 'DeleteView' article.id %}" method="POST">
    {% csrf_token %}
    <input type="hidden" value="{{ article.views.id }}">
    <input type="submit" value="Delete">
</form>
</div>

urls.py

url(r'^delete/(?P<id>\d+)/$', DeleteView.as_view(), name="DeleteView"),

The faults are problably on : the views : line 3 | the template : line 2

I am missing something but I couldn't figure it out. How can I get through this problem?

3

There are 3 answers

0
Aamir Rind On BEST ANSWER

The problem is with your post method of DeleteView, there you are passing id which is a python built-in function rather you need to get the id from kwargs:

Problem:

class DeleteView(View):
    def post(self, request, *args, **kwargs):
        article = get_object_or_404(Article, id=id) # <--------

Solution:

class DeleteView(View):
    def post(self, request, *args, **kwargs):
        article = get_object_or_404(Article, id=kwargs['id']) # <--------
3
Daniel Roseman On

You need to pass the model class, so that the function knows what type of object it is trying to get.

article = get_object_or_404(Article, id=request.POST.get('article_id', ''))
0
knbk On

In post(), you're not passing the id kwarg, but you're passing the built-in function id. You need to use kwargs['id'] instead, as you did in get().