Modify template name Django

0

I am generating a view to search for products and I want to modify it to also search for users when the name starts with '@'.

Right now I have this view:

class BusquedaView(FilterView):
    model = Producto
    filterset_class = BusquedaFilter
    template_name = 'frontend/filtrado.html'

    def get_context_data(self, **kwargs):
        context = super(BusquedaView, self).get_context_data(**kwargs)
        if self.request.GET.get('nombre')[0] == '@':
            perfiles = Perfil.objects.filter(
                        usuario__username__istartswith = self.request.GET.get('nombre')[1:])
            context['perfiles'] = perfiles
        else:
            return context

If you enter the @ character at the beginning, modify the variable template_name with a different template in which the user's presentation is.

I do not know if there is any way to do that or directly I would have to send it to another URL in which the function get_context_data is personalized.

    
asked by F Delgado 16.03.2018 в 17:16
source

1 answer

1

You can try doing this by overwriting the get method of your class:

# ...
from django.shortcuts import render


class BusquedaView(FilterView):
    model = Producto
    filterset_class = BusquedaFilter
    template_name = 'frontend/filtrado.html'

    def get_context_data(self, **kwargs):
        context = super(BusquedaView, self).get_context_data(**kwargs)
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(*args, **kwargs)
        template_name = self.template_name
        nombre = request.GET.get('nombre')
        if nombre.startswith('@'):
            perfiles = Perfil.objects.filter(
                        usuario__username__istartswith=nombre[1:]
            )
            context['perfiles'] = perfiles
            template_name = 'mi_otro_template.html'
        return render(request, template_name, context)

It's simple, in get_context_data() you could not do it simply because its function is to build the context (the dictionary), but if you do it from get() you have the option to change the name of the template since get() must return a response (using render() in this case).

Eye: Notice that I'm using startswith() instead of searching for the position by its 0 index. It's safer.

    
answered by 16.03.2018 / 21:18
source