V
V
Vitaly2016-07-17 17:44:55
Django
Vitaly, 2016-07-17 17:44:55

How to remove an object from a Django database?

Greetings. I'm making a blog in Django, I created a "delete" button on the article's detailed view page, but I can't delete the object from the database.
Url.py

....
    url(r'^(?P<a_id>\d+)/del', del_post, name='del_view'),
    ....

Views.py
def del_post(request, a_id):

    article = Article.objects.get(id=a_id)
    if request.user == article.author:
        Article.objects.get(id=a_id).delete()
        return redirect('/')

    else:
        return HttpResponse('Nonono!')

A piece from a template. (detailed view of the article)
<a href= {% url 'del_view' a_id=Article.id %}> (Удалить) </a>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vitaliy, 2016-07-18
@MrCute

Solved the problem. It turned out that I had another model attached to the Article model, which I forgot about. Deleted it and everything worked.

V
Vladimir Kuts, 2016-07-18
@fox_12

Try like this:

def del_post(request, a_id):
  article = Article.objects.get(id=a_id)
    if request.user == article.author:
        article.delete()
        return redirect('/')

    else:
        return HttpResponse('Nonono!')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question