2

Help me please to understand how to make the delete button, its must to delete a Cat

class Cat(models.Model):
    class Meta():
        db_table = "cat"

    paw = models.IntegerField(default=4)
    name = models.CharField(max_length=30, null=False, default='Cat')
    age = models.IntegerField(default=False, null=False)
    species = models.CharField(max_length=50, blank=True)
    hairiness = models.IntegerField(default=False, null=False)

    def __str__(self):
        return self.name

This is my views.py, hope you can help. (it's need for my job interview on Monday)

from django.shortcuts import render, get_object_or_404
from .models import Cat
from .forms import CatForm
from django.shortcuts import redirect

def home(request):
    template = "base.html"
    queryset = Cat.objects.all()
    context = {
        "object_list": queryset
    }
    return render(request, template, context)

def new_cat(request):
    if request.method == "POST":
        form = CatForm(request.POST)
        if form.is_valid():
            cat = form.save(commit=False)
            cat.save()
            return redirect('/', pk=cat.pk)
    else:
        form = CatForm()
    return render(request, 'new_cat.html', {'form': form})

def cat_edit(request, pk):
    cat = get_object_or_404(Cat, pk=pk)
    if request.method == "POST":
        form = CatForm(request.POST, instance=cat)
        if form.is_valid():
            cat = form.save(commit=False)
            cat.save()
            return redirect('/', pk=cat.pk)
    else:
        form = CatForm(instance=cat)
    return render(request, 'new_cat.html', {'form': form})

site is asc to addd more details, but i just don't know what else, i can add.

from django.conf.urls import url
from . import views


urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'^new/$', views.new_cat, name='new_cat'),
    url(r'^edit/(?P<pk>[0-9]+)/$', views.cat_edit, name='cat_edit'),
]
1
  • you can try do the same as your cat_edit, show you view, please Commented Sep 1, 2017 at 15:03

1 Answer 1

20

At first, you should create a cat_delete view, which should look something like this:

def cat_delete(request, pk):
    cat = get_object_or_404(Cat, pk=pk)  # Get your current cat

    if request.method == 'POST':         # If method is POST,
        cat.delete()                     # delete the cat.
        return redirect('/')             # Finally, redirect to the homepage.

    return render(request, 'template_name.html', {'cat': cat})
    # If method is not POST, render the default template.
    # *Note*: Replace 'template_name.html' with your corresponding template name.

Then, you should map this view in your urls.py:

from django.conf.urls import url
from . import views

app_name = 'cats'
# Note that app_name is added here!
# It is used as a namespace in order to reverse your urls better.
# See usage in template.

urlpatterns = [
    # ...
    url(r'^delete/(?P<pk>[0-9]+)/$', views.cat_delete, name='cat_delete')
]

In your template, you should create a form with delete button, which will simply send a POST request to the delete view:

<form action="{% url 'cats:cat_delete' cat.id %}" method="post">
    {% csrf_token %}
    <input type="submit" value="Delete cat">
</form>

Look closely on the form's action:

{% url 'cats:cat_delete' cat.id %}

Here I am using the app_name from urls.py that I previously added in order to resolve your urls by name, not by path. Now cats:cat_delete will evaluate to cats/delete/<pk>. And of course you pass the cat.id.

This should do the trick with deleting instance of your Cat model. Hope I helped.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, for your help and really big answer, now i understand my mistake))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.