I would like to get an explanation explicit enough, the documentation with django is excellent but in some cases a bit confusing, I would like to know how to use both methods and a practical case if possible.
Thanks
I would like to get an explanation explicit enough, the documentation with django is excellent but in some cases a bit confusing, I would like to know how to use both methods and a practical case if possible.
Thanks
as its name indicates, it obtains the context data. They are the data, variables, objects, etc., that you will pass to the template to make them. For example, where you would pass a form in case you need a template with 2 or more forms.
I give you an example of how it would work:
class TemplateDetalle(DetailView):
model = ModelTemplate
form_class = TemplateForm
template_name = "backend/template/templatedetalle.html"
success_url = reverse_lazy('templates')
def get_context_data(self,**kwargs):
context = super(TemplateDetalle, self).get_context_data(**kwargs)
context['grupo'] = self.request.user.groups.get().name
context['form2'] = TemplateForm2()
return context
This function is responsible for obtaining the objects of the model that you indicate in the model variable of your class. This function by default obtains the queryset of the call model.objects.all()
. You can rewrite this function in the same way as get_context_data()
to indicate some special restriction you need in that view.
I add an example and explain it:
def get_queryset(self,perfil,npagina=1):
consulta = Producto.objects.filter(Q(perfil = perfil), Q(estado_rev=4)|Q(estado_rev=6)).order_by('-f_act')
lista_productos = []
for p in consulta:
foto = Foto.objects.filter(producto = p.id)
lista_productos.append({'producto':p,'foto':foto[0],'contador_like':contador_like(p)})
paginacion = Paginator(lista_productos,80)
if len(paginacion.page(1)) == 0:
return None
else:
return paginacion.page(npagina)
In this example I am getting all the objects of the Product model filtering by the query that you can see and getting other related data like the "likes" counter to create pages. This way you do not get all the products that exist since that could generate a very heavy load for the server. In this way using the function get_contenxt_data
you can add the line context['productos']=self.get_queryset(npagina=self.request.GET.get('page'),perfil=perfil)
and in your template you would have the variable {{productos}}
that would contain a list of 80 objects.