serj
serj

Reputation: 189

Django redirect to template passing model

The think I'm trying to do is to redirect to the same page where user was when deleted an item. After delete using "django.views.generic.edit" (DeleteView) I can collect all needed information into model and get the specific category that I need. The question is how can I create this request url to go?

This way I get to http://127.0.0.1:8000/productlist/floor/

<a class="dropdown-item" href="{% url 'productlist' 'floor' %}" >

views.py

class LampDelete(DeleteView):
model = Lamp
#success_url = reverse_lazy('index')

def get_success_url(self):
    categ = self.object.category
    lamps = Lamp.objects.filter(category=categ)
    return redirect('productlist', {'lamps': lamps})

urls.py

urlpatterns =[
url(r'^$', views.index, name='index'),
url(r'^productlist/([a-z0-9]+)/$', views.productlist, name='productlist'),
url(r'^accounts/', include('allauth.urls')),
url(r'productlist/(?P<pk>[0-9]+)/delete/$', views.LampDelete.as_view(), name='lamp-delete'),]

So what method should I use and how to redirect to my template with selected category model. If somebody could provide an example would be very thankful.

Upvotes: 1

Views: 1536

Answers (1)

vishes_shell
vishes_shell

Reputation: 23554

Actually you still have object in .get_success_url(),

From source code:

class DeletionMixin(object):
    def delete(self, request, *args, **kwargs):
        """
        Calls the delete() method on the fetched object and then
        redirects to the success URL.
        """
        self.object = self.get_object()
        success_url = self.get_success_url()
        self.object.delete()
        return HttpResponseRedirect(success_url)

As you can see, firstly it computes success_url and then it deletes the object.

What you did wrong:

  1. Instead of supplying url as str object you called redirect which triggers redirect and skips the whole process of deletion.
  2. Make redirect to view with url argument supplying queryset and not str as it has been waiting ([a-z0-9]+)

I believe that in productlist view you expect some sort of name of category, by which your products been filtered

So what you can do:

  1. Return valid str object in .get_success_url()

E.g.

class LampDelete(DeleteView):
    model = Lamp

    def get_success_url(self):
        category = self.object.category
        return reverse('productlist', args=[category])

Upvotes: 2

Related Questions