Horai Nuri
Horai Nuri

Reputation: 5578

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

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?

Upvotes: 2

Views: 1277

Answers (3)

Daniel Roseman
Daniel Roseman

Reputation: 599630

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

Upvotes: 3

Aamir Rind
Aamir Rind

Reputation: 39659

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

Upvotes: 2

knbk
knbk

Reputation: 53679

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().

Upvotes: 1

Related Questions