Space guy
Space guy

Reputation: 415

How to Link a template with the url of a class-based-view?

I'm trying to create a link <a> that redirects me to an url of a view DeleteView. I want that link to be in the template of my app. By clicking on that link you will get redirected to the url of the DeleteView.

Here's the DeleteView:

class imagenDelete(DeleteView):
model = imagen

def get_id(self, request):
    getall = imagen.objects.all()

Here's the urls.py:

urlpatterns = [

path('', views.galeria, name='galeria'),
path('delete/<int:pk>', views.imagenDelete.as_view(), name='deletegaleria'),

]

Here's the link im trying to create in the template of my App:

<a style="font-size: 3rem;" href="{% url 'deletegaleria' pk %}">Click to delete</a>

The problem is that in the url i must pass the id of the image that you want to delete. If i'd write it like this {% url 'deletegaleria' 14 %} it works, te link is shown in the template and it redirects you to the url to delete the image with id = 14.

If i'd do it like this:

{% for on in getall %}
<a style="font-size: 3rem;" href="{% url 'deletegaleria' o.id %}">Click to delete</a>
{% endfor %}

This doesn't give me any error but doesn't show the link in the template.

And if i do this way {% url 'deletegaleria' pk %} which is basically no iterating i get the next error:

Reverse for 'deletegaleria' with arguments '('',)' not found. 1 pattern(s) tried: ['galeria/delete/(?P[0-9]+)$']

Upvotes: 3

Views: 923

Answers (3)

Space guy
Space guy

Reputation: 415

So the problem was that i was working with a Function-Based-View to render my template and Class-Based-View to Delete some objects.

What i did to make it work was only work with class-based-views.

For anyone wondering what the next code does: I created two views. One for showing images. Another one shows a form that allows users to upload their own images. I'm also saving the User that upload the image when the method is POST. Later i create the DeleteView which will delete images only if the logged in user is the same that uploaded the image.

views.py:

class galeriaListView(ListView):
    model = imagen
    template_name = "galeria/galeria.html"
    imagenes = imagen.objects.all()
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['imagenes'] = self.imagenes
        return context

class formularioimagenListView(ListView):
    model = imagen
    formulario_subir_imagen = formulario_img()
    template_name = "galeria/formulario_subir_imagen.html"
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['formulario_subir_imagen'] = self.formulario_subir_imagen
        return context
    def post(self, request, *args, **kwargs):
        formulario_subir_imagen = formulario_img(request.POST, request.FILES)
        if formulario_subir_imagen.is_valid():
            profile = formulario_subir_imagen.save(commit=False)
            profile.autor = request.user
            profile.save()
            return redirect("/galeria/")

class imagenDelete(DeleteView):
    model = imagen
    success_url = "/galeria/"
    template_name = "galeria/delete_imagen.html"
    def dispatch(self, request, *args, **kwargs):
        self.obj = self.get_object()
        if self.obj.autor != self.request.user:
            return HttpResponseForbidden("Cannot delete other's posts")
        return super(imagenDelete, self).dispatch(request, *args, **kwargs)
    

urls.py:

    path('', views.galeriaListView.as_view(), name='galeria'),
    path('<pk>/delete/', views.imagenDelete.as_view(), name='deleteimagen'),
    path('subir_imagen', views.formularioimagenListView.as_view(), name='subirimagen'),
    path('borrar_imagen', views.borrar_imagenListView.as_view(), name='opcionesimagenesaborrar'),

And the <a> in the template would look like this.

template.html:

<a style="font-size: 3rem;" href="{% url 'subirimagen' %}">Click para subir imagen</a>
<a style="font-size: 3rem;" href="{% url 'opcionesimagenesaborrar' %}">Click para borrar tus imagenes</a> 

Upvotes: 2

taha maatof
taha maatof

Reputation: 2165

you have

path('delete/<int:pk>', views.imagenDelete.as_view(), name='deletegaleria'),

so you ve got to use pk in your template

{% for on in getall %}
  <a style="font-size: 3rem;" href="{% url 'deletegaleria' on.pk %}">Click to delete</a>
{% endfor %}

Upvotes: 0

SDRJ
SDRJ

Reputation: 540

@SpaceCat69- Firstly, let me understand something. What I think you want is this

  1. You have a listview which will render all your data. And let's assume your data is in table format. There will be delete link next to each row
  2. When clicking on the delete link, it should redirect to the delete view.
  3. So, you need to show us how you are rendering the listview of the objects.

Why would you even create get_id in your deleteview? What purpose does it serve ? Why would you want to pass the entire model queryset in a DeleteView. Your DeleteView should have one queryset based on the kwargs passed in the URL.

And fyi- Your deleteview is incomplete

An example of a deleteView

class ProductDelete(LoginRequiredMixin, SuccessMessageMixin, DeleteView):
# specify the model you want to use
model = Product
template_name = "catalog/product/delete_product.html"
success_message = "Product Deleted Successfully"

def get_success_url(self):
    return reverse("catalog:product_list")

Upvotes: 0

Related Questions